Sometimes having Excel export problems - excel

I have a problem, I'm importing cycling a Table to Excel.
My code is look like this :
#WINAPI
#Excel
SysExcelApplication excel;
SysExcelWorkbooks books;
SysExcelWorkbook book;
SysExcelWorksheets sheets;
SysExcelWorksheet sheet;
SysExcelCells cells;
SysExcelCell cell;
SysExcelRange columns;
while select myTable
{
cell = sheet.cells().item(row, col);
cell.value(myTable.FieldI);
sheet.columns().autoFit();
col++;
cell = sheet.cells().item(row, col);
cell.value(myTable.FieldII);
sheet.columns().autoFit();
col++;
row++;
col=1;
}
// when the cycle end save my file
But sometimes I give an error look like message debug
"Wrong argument types in variable assignment"
or
"The number of arguments provided is different from the number of arguments accepted by the method"
But the weird thing is if i try againg to re-launch the export I will not get the errors.
I have this problem
I have same code and same data.
When I generate the file the excle rows are perfect.
I have this problem in 50% of these cases.
The rows created are 1700 more less.
What does it depend on? I have a lot rows? Or other?
I share the same question found on web Some question ,I tried to use, but did't solved my problem:
I add more information not slved my problem change settings
Thanks in advice,
enjoy

Yes, when develop any export Excel had this problem, when many rows. If there are few rows it works perfect.
For this cases always change the excel export for CSV export. The code to export csv file never fail and work perfect!
Here I leave an example to export csv file with 5 rows.
Code:
static void ExportCSV(Args _args)
{
Commaio file;
container lineCSV;
#File
str DatosLinea[500];
int _i;
str filename;
Dialog dialog;
DialogField dialogFileName;
;
dialog = new Dialog("Path CSV");
dialogFileName = dialog.addField(ExtendedTypeStr("FilenameSave"),"Path File:");
if (dialog.run())
{
filename = dialogFileName.value();
}
if (!filename)
{
return;
}
file = new Commaio((filename), 'W'); //Path + file name.csv
file.outFieldDelimiter(';');
if( !file || file.status() != IO_Status::Ok)
{
throw error("File Cannot be opened");
}
DatosLinea[1] = "Col 1";
DatosLinea[2] = "Col 2";
DatosLinea[3] = "Col 3";
DatosLinea[4] = "Col 4";
DatosLinea[5] = "Col 5";
_i = 1;
lineCSV = conNull();
while(_i <= 5){
lineCSV += DatosLinea[_i];
_i += 1;
}
file.write(lineCSV);
info("Export end");
}

Related

Export PDF file from Excel template with Qt and QAxObject

The project I am currently working on is to export an Excel file to PDF.
The Excel file is a "Template" that allows the generation of graphs. The goal is to fill some cells of the Excel file so that the graphs are generated and then to export the file in PDF.
I use Qt in C++ with the QAxObject class and all the data writing process works well but it's the PDF export part that doesn't.
The problem is that the generated PDF file also contains the data of the graphs while these data are not included in the print area of the Excel template.
The PDF export is done with the "ExportAsFixedFormat" function which has as a parameter the possibility to ignore the print area that is "IgnorePrintAreas" at position 5. Even if I decide to set this parameter to "false", so not to ignore the print area and therefore to take into account the print area, this does not solve the problem and it produces the same result as if this parameter was set to "true".
I tried to vary the other parameters, to change the type of data passed in parameter or not to use any parameter but it does not change anything to the obtained result which is always the same.
Here is the link to the "documentation" of the export command "ExportAsFixedFormat":
https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.exportasfixedformat
I give you a simplified version of the command suite that is executed in the code:
Rapport::Rapport(QObject *parent) : QObject(parent)
{
//Create the template from excel file
QString pathTemplate = "/ReportTemplate_FR.xlsx"
QString pathReporter = "/Report"
this->path = QDir(QDir::currentPath() + pathReporter + pathTemplate);
QString pathAbsolute(this->path.absolutePath().replace("/", "\\\\"));
//Create the output pdf file path
fileName = QString("_" + QDateTime::currentDateTime().toString("yyyyMMdd-HHmmssff") + "_Report");
QString pathDocument = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation).append("/").replace("/", "\\\\");
QString exportName(pathDocument + fileName + ".pdf");
//Create the QAxObjet that is linked to the excel template
this->excel = new QAxObject("Excel.Application");
//Create the QAxObject « sheet » who can accepte measure data
QAxObject* workbooks = this->excel->querySubObject("Workbooks");
QAxObject* workbook = workbooks->querySubObject("Add(const QString&)", pathAbsolute);
QAxObject* sheets = workbook->querySubObject("Worksheets");
QAxObject* sheet = sheets->querySubObject("Item(int)", 3);
//Get some data measure to a list of Inner class Measurement
QList<Measurement*> actuMeasure = this->getSomeMeasure() ; //no need to know how it’s work…
//Create a 2 dimentional QVector to be able to place data on the table where we want (specific index)
QVector<QVector<QVariant>> vCells(actuMeasure.size());
for(int i = 0; i < vCells.size(); i++)
vCells[i].resize(6);
//Fill the 2 dimentional QVector with data measure
int row = 0;
foreach(Measurement* m, actuMeasure)
{
vCells[row][0] = QVariant(m->x);
vCells[row][1] = QVariant(m->y1);
vCells[row][2] = QVariant(m->y2);
vCells[row][3] = QVariant(m->y3);
vCells[row][4] = QVariant(m->y4);
vCells[row][5] = QVariant(m->y5);
row++;
}
//Transform the 2 dimentional QVector on a QVariant object
QVector<QVariant> vvars;
QVariant var;
for(int i = 0; i < actuMeasure.size(); i++)
vvars.append(QVariant(vCells[i].toList()));
var = QVariant(vvars.toList());
//Set the QVariant object that is the data measure on the excel file
sheet->querySubObject("Range(QString)", "M2:AB501")->setProperty("Value", var);
//Set the fileName on the page setup (not relevant for this example)
sheet->querySubObject("PageSetup")->setProperty("LeftFooter", QVariant(fileName));
//Export to PDF file with options – NOT WORKING !!!
workbook->dynamicCall("ExportAsFixedFormat(const QVariant&, const QVariant&, const QVariant&, const QVariant&, const QVariant&)", QVariant(0), QVariant(exportName), QVariant(0), QVariant(false), QVariant(false));
//Close
workbooks->dynamicCall("Close()");
this->excel->dynamicCall("Quit()");
}
A this point I really need help to find a way to solve this problem.
I also wonder if this is not a bug of the QAxObject class.
I finally found a solution on another forum.
If anyone needs help, I'll leave the link to the answer.

EPPlus corrupt Excel file when having more than 65,530 rows

I'm running into an issue with EPPlus when there are more than 65,530 rows that have a column with a hyperlink. The example below is configured to create 65,530 rows. With this number it will create the Excel file correctly (not corrupt). Once you run it with anything over 65,530, the Excel file will be created but when you open it, Excel will report that is corrupt. Any ideas how to solve this issue?
try
{
int maxRowsToCreate = 65530; //-- no errors will be generated
//int maxRowsToCreate = 65531; //-- error will be generated. The Excel file will be created but will give an error when trying to open it.
string report = string.Format("D:\\temp\\hypelinkIssue-{0}.xlsx", maxRowsToCreate.ToString());
if (File.Exists(report))
{
File.Delete(report);
}
using (ExcelPackage pck = new ExcelPackage(new System.IO.FileInfo(report)))
{
//Add the Content sheet
var ws = pck.Workbook.Worksheets.Add("Catalog");
ws.View.ShowGridLines = true;
var namedStyle = pck.Workbook.Styles.CreateNamedStyle("HyperLink"); //This one is language dependent
namedStyle.Style.Font.UnderLine = true;
namedStyle.Style.Font.Color.SetColor(Color.Blue);
ws.Column(1).Width = 100;
int rowIndex = 0;
for (int i = 0; i < maxRowsToCreate; i++)
{
rowIndex += 1;
string fullFilePath = string.Format("D:\\temp\\{0}", Path.GetRandomFileName());
ws.Cells[rowIndex, 1].StyleName = "HyperLink";
ws.Cells[rowIndex, 1].Hyperlink = new Uri(string.Format(#"file:///{0}", fullFilePath));
ws.Cells[rowIndex, 1].Value = fullFilePath;
}
pck.Save();
}
System.Diagnostics.Process.Start(report);
}
catch (Exception ex)
{
throw ex;
}
The issue occurs when using ".Hyperlink". If instead I use ".Formula" and populate it with the "=HYPERLINK" Excel formula, it works fine. I was able to create 250k records with unique hyperlink using this approach. I did not try more than 250k but hopefully it will work fine.
Thanks for pointing me in the right direction.
/*
This only works with LESS than 65,530 hyperlinks
*/
ws.Cells[rowIndex, 1].StyleName = "HyperLink";
ws.Cells[rowIndex, 1].Hyperlink = new OfficeOpenXml.ExcelHyperLink(fullFilePath, ExcelHyperLink.UriSchemeFile);
ws.Cells[rowIndex, 1].Value = fullFilePath;
/*
This works with more that 65,530 hyperlinks
*/
string cellFormula = string.Format("=HYPERLINK(\"{0}\")", filePath);
ws.Cells[rowIndex, 1].Formula = cellFormula;
This is because Excel limits the amount of unique URLs in a file to 65,530. You should try to insert them as text, instead of a url.
For a possible solution, take a look at this answer.

dropdown Validation not working if it exceeds 50 rows in the Export To Excel

I am generating Excel File(.xlsx) using apache poi jar (poi-ooxml-3.9.jar), I added dropdown validation for 10 columns in my excel file, If I generate the Excel File with 50 rows, drop down validation is working. If it exceeds more than 50 rows, drop down validation is not coming in the Excel File, When I open the excel File I get the message as "We found a problem with some content in fileName.xlsx. Do you want us to try to recover as much as we can ? If you trust the source of this workbook, click Yes ". when click on Yes, all the dropdown validation it is removing. Kindly need solution to fix this issue.
Do not create DataValidationConstraint for each single cell but only for each varying list you need. Then create DataValidation using those DataValidationConstraint for continuous CellRangeAddressList which are as big as possible and also are not all single cells.
Example creates ten different list validations for column 1 to 10 in rows 1 to 10000.
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
class DataValidationList {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook(); // or new HSSFWorkbook
Sheet sheet = workbook.createSheet("Data Validation");
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
for (int col = 0; col < 10; col++) {
DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(
new String[]{"Col "+(col+1)+" one","Col "+(col+1)+" two","Col "+(col+1)+" three"});
CellRangeAddressList addressList = new CellRangeAddressList(0, 9999, 0, col);
DataValidation validation = dvHelper.createValidation(
dvConstraint, addressList);
if(validation instanceof XSSFDataValidation) {
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
}
else {
validation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(validation);
}
String filename;
if(workbook instanceof XSSFWorkbook) {
filename = "DataValidationList.xlsx";
} else {
filename = "DataValidationList.xls";
}
FileOutputStream out = new FileOutputStream(filename);
workbook.write(out);
out.close();
workbook.close();
}
}

File error on opening spreadsheet created with Spreadsheet::WriteExcel

I was using Spreadsheet::WriteExcel to create xls file using perl. When the range of spreadsheet increased, the Microsoft excel shows an alert before opening the file "File Error: Data may have been lost".
Please help me to solve this.
Here is the code
my $row = 2;
foreach my $sid(array of students objects)
{
my $s = $students->{$sid};
my $cc = 0;
my $wall = f1($x, $y, $z);#f1 is a method returns hash of arrays that have to write on excel having keys #key_array
foreach my $key (#key_array) {
my $t_row = $row;
my $i_c = 0;
my $t_col = 0;
my $m_row = $max_row;
while($m_row > 0){
$t_col = 3+($cc*7);
if($cc == 0){
$ws->write($t_row, 0,
[$s->{first_name}, $s->{last_name}, $s->{l_name}], $fmt_wrap
);
}
if(defined $wall->{$key}->[$i_c] ){
$ws->write($t_row, $t_col, $wall->{$key}->[$i_c], $fmt_wrap);
} else {
$ws->write($t_row, (3+$cc*7),["","","","","","",""], $fmt_wrap);
}
$t_row++;
$i_c++;
$m_row--;
}#while loop
$ws->write($t_row-1, 3+$company_format*$max_step,
[ (scalar keys %{$s->{videos}}), $s->{total_pageviews} ], $fmt
);
$cc++;
$t_row = 2;
}#foreach loop
$row+=$max_row;
}#foreach student array
I have found answer. In the code there was a line which write data into a cell multiple times. So i found that multiple write attempt to a particular cell can cause file corruption.

Comparing excel value with console output using selenium web driver

I am storing excel values in 1st array and console output values in 2nd array. Then I am comparing excel value with console output one by one .I have debug code and it stores value proper in arrays. But it always print "FALSE" even if value matches true.
My latest code is given below :
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=1YaGVMutHcXN8gf39ID4Aw&gws_rd=ssl#q=what+is+software+testing");
java.util.List<WebElement> links = driver.findElements(By.tagName("h3"));
int sizecount = links.size();
System.out.println(sizecount);
//READING DATA FROM EXCEL FROM 1ST COLUMN
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
String exceldata[] = new String[20];
for (int i=0;i<=sh.getLastRowNum();i++)
{
HSSFRow row = sh.getRow(i);
exceldata[i]= row.getCell(count).toString();
System.out.println(exceldata[i]);
}
String linkdata[] = new String[20];
for(int j=1;j<=links.size()-1;j++)
{
linkdata[j] = links.get(j).getText();
System.out.println(linkdata[j]);
}
for(int k=0;k<links.size()-1;k++)
{
if(exceldata==linkdata)
{
System.out.println("TRUE");
}
else
{
System.out.println("FALSE");
}
}
driver.close();
}
}
Note : I have tried with operator == and .equals both.
I've told you few issues in your program, you can modify your program according to that.
Issue 1
When you are storing the value in exceldata and linkdata array, you are taking different index, exceldata array is storing value from index 0 and linkdata is storing value from index 1, so you need to modify your program something like below:
for(int k=0;k<links.size()-1;k++){
if(exceldata[k].trim().equals(linkdata[k+1].trim())){
System.out.println("TRUE");
}else{
System.out.println("FALSE");
}
}
There was one more issue, I've already told you.
You are good to go now.

Resources