I have an Excel sheet that has multiple sheets and is filled with formulas. There are some blank cells in this sheet that are to be filled by a user and saved to get different results with different inputs.
I take the inputs from the users and write these values to blank cells using EPPlus for c#. After this, I call the calculate function on this excel sheet and save the sheet. When I read this saved sheet using ExcelDataReader, the value that I am getting is 0 for some cells and proper values for some cells. But when I open this sheet manually, all the cells have properly calculated values.
Kindly help me so that I can get properly calculated values from that sheet using ExcelDataReader
FileStream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.ReadWrite);
IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream);
var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true,
}
});
var workbook = reader.AsDataSet();
var sheet = dataSet.Tables[index];
I am using this code to read from the excel.
Note - When I write to the excel file (say abc.xlsx) using c# and try to read from the file the values that I get are invalid but when I open the file (abc.xlsx) manually and click on save option in MS Excel or WPS writer and after that if I read from this file I get proper values.
Following is the code that I use to write to excel using EPPlus
FileInfo fileInfo = new FileInfo(filePath);
ExcelPackage excelPackage = new ExcelPackage(fileInfo);
excelPackage.Workbook.CalcMode = ExcelCalcMode.Manual;
var inputDataWorksheet = excelPackage.Workbook.Worksheets.Where(x => x.Name.Contains("Input Data")).FirstOrDefault();
var resultSheet1 = excelPackage.Workbook.Worksheets.Where(x => x.Name.Contains("SMH code wise-A")).FirstOrDefault();
var resultSheet2 = excelPackage.Workbook.Worksheets.Where(x => x.Name.Contains("SMH code wise-B")).FirstOrDefault();
var resultSheet3 = excelPackage.Workbook.Worksheets.Where(x => x.Name.Contains("SMH Process wise")).FirstOrDefaul
//dummy code
foreach (var input in allAnswers))
{
inputDataWorksheet.Cells[input.Item2, input.Item3].Value = input.Item1;
}
var calcOptions = new ExcelCalculationOption();
calcOptions.AllowCircularReferences = true;
resultSheet1.Cells[1, 1, lastRow, lastCol].Calculate(calcOptions);
resultSheet2.Cells[1, 1, lastRow, lastCol].Calculate(calcOptions);
resultSheet3.Cells[1, 1, lastRow, lastCol].Calculate(calcOptions);
excelPackage.Workbook.CalcMode = ExcelCalcMode.Automatic;
excelPackage.SaveAs(new FileInfo(exportPath));
excelPackage.Dispose();
After writing to excel, I try to read the value from resultSheet1, resultSheet2 and resultSheet3.