For some reason ExcelReaderFactory.CreateOpenXmlReader()
throws NullReferenceException
while trying to read .xlsx files created by code. For document creating I use OpenXml library. Here is the way of creating .xlsx I used in my code:
public void CreateExcelFile(string filePath, string[][] rowsData)
{
using (SpreadsheetDocument spreedDocument = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = spreedDocument.WorkbookPart;
if (workbookPart == null)
{
workbookPart = spreedDocument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
}
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
if (workbookPart.Workbook.Sheets == null)
{
workbookPart.Workbook.AppendChild(new Sheets());
}
var sheet = new Sheet()
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
var excelRowIndex = 1;
foreach (var row in rowsData)
{
var excelRow = new Row {RowIndex = (UInt32) excelRowIndex};
foreach (var value in row)
{
excelRow.AppendChild(AddCellWithText(value));
}
sheetData.AppendChild(excelRow);
excelRowIndex++;
}
workbookPart.Workbook.Sheets.Append(sheet);
workbookPart.Workbook.Save();
}
}
public static Cell AddCellWithText(string text)
{
var cell = new Cell {DataType = CellValues.InlineString};
var inlineString = new InlineString();
var cellText = new Text {Text = text};
inlineString.AppendChild(cellText);
cell.AppendChild(inlineString);
return cell;
}
The issue happens only for .xlsx files generated by code. For documents created in Excel everything work fine. So I think that there are some issues in the files generating. Any ideas?
Update: This is the cocde where the exception happens:
static DataSet ReadExcelFile(string filePath, bool isFirstRowColumnNames = false)
{
DataSet result;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var excelReader = ExcelReaderFactory.CreateOpenXmlReader(fs))
// ...