My method is opening an Excel file. This sheet has 6 rows with header data and then 1 row with values and formulas.
I add data from an SQL Query to this file and copy the formula to all other rows.
When I open this file in LibreOffice I can see the formulas are correct, but the values are '0'.
When I select the cell and hit F9 (recalculate), the formula is executed and the proper value is shown.
Of course, I need to recalculate in my code. I've read several posts already try to get this to work, so far without any luck.
Here's my code:
public MemoryStream ExportLiv(List<LivExportDto> data, DateTime startPeriod, DateTime endPeriod)
{
var stream = new MemoryStream();
//Create an instance of ExcelEngine.
using (var excelEngine = new ExcelEngine())
{
var application = excelEngine.Excel;
//Set the default application version as Excel 2013.
application.DefaultVersion = ExcelVersion.Excel2013;
application.EnableIncrementalFormula = true;
excelEngine.ThrowNotSavedOnDestroy = true;
//Open a workbook with a worksheet.
var workbook = application.Workbooks.Open(new MemoryStream(Resource.LIV2017));
// Template was made with Dutch Excel:
workbook.SetSeparators(',', ';');
//Access first worksheet from the workbook instance.
var worksheet = workbook.Worksheets[0];
//Formula calculation is enabled for the sheet.
worksheet.EnableSheetCalculations();
// Fill header:
worksheet.Range["I1"].Value = "Foo";
// Set start values:
var row = 7;
foreach (var dto in data)
{
var column = 1;
worksheet.Range[row, column].Text = dto.EmployeeNumber;
worksheet.Range[row, ++column].Text = dto.Initials;
worksheet.Range[row, ++column].Text = dto.Prefix;
worksheet.Range[row, ++column].Text = dto.Surname;
worksheet.Range[row, ++column].DateTime = dto.BirthDate;
row++;
}
try
{
// Update formulas:
row--;
worksheet.Range["G7:G" + row].Formula = worksheet.Range["G7"].Formula; // Age
// Recalculate formulas, doesn't seems to make any difference:
string dummy = null;
foreach (var range in worksheet.UsedCells)
{
if (range.HasFormula)
dummy = range.CalculatedValue;
}
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
//Formula calculation is disabled for the sheet.
worksheet.DisableSheetCalculations();
// Show borders:
worksheet.UsedRange.BorderAround();
worksheet.UsedRange.BorderInside();
if (!string.IsNullOrEmpty(saveAsFilename))
{
// Debug mode:
//Save the workbook to disk in xlsx format.
workbook.SaveAs(saveAsFilename);
Debug.WriteLine("File saved as " + saveAsFilename);
}
workbook.SaveAs(stream);
//Resetting Memory stream position.
stream.Position = 0;
workbook.Close();
}
return stream;
}
My first question is how to recalculate the formulas? So when opening in LibreOffice the cells have the proper values.
I don't have a copy of Excel, so perhaps in Excel, this is also an issue.
My second question: Am I doing the filling of the sheet in the most efficient manner? I have up to 50,000 records to export and that is taking more than 60 seconds.
Thanks.