由于某些原因,ExcelReaderFactory.CreateOpenXmlReader()
在尝试读取由代码创建的.xlsx文件时抛出NullReferenceException
。对于文档创建,我使用OpenXml库。这是创建在我的代码中使用的.xlsx的方法:
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;
}
此问题仅发生于由代码生成的.xlsx文件。对于在Excel中创建的文档,一切正常。因此,我认为文件生成中存在一些问题。 有任何想法吗?
更新:这是发生异常的代码:
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))
// ...