读取ExcelWorksheet时出现C#ArgumentOutOfRangeException

我正在阅读OfficeOpenXml.ExcelWorksheet并获取集合中间的ArgumentOufOfRangeException。

我正在读这个process.Information = sheet.Cells[line, i++].Text; 。 在这一行上, i = 22sheet.Dimension.Column = 28工作表#列

我值 当我debugging并枚举集合时,我发现在.Value方法显示正确的值时,Exception在方法.Text上抛出。

列举的集合

根据exception堆栈跟踪,System.Text.StringBuilder.Insert()方法抛出exception

跟踪

—-编辑—-在接受答案后,我意识到问题不仅在于阅读。 我用额外的列回复相同的文件(导入成功或不成功),而当我做表格格式时,我再次得到同样的错误,全部由于System.Text.StringBuilder.Insert()方法。 我想sheet.Column(22).AutoFit()sheet.Column(22).AutoFit()这是堆栈跟踪

 at System.Text.StringBuilder.Insert(Int32 index, Char* value, Int32 valueCount) at System.Text.StringBuilder.Insert(Int32 index, Char value) at OfficeOpenXml.Style.XmlAccess.ExcelNumberFormatXml.ExcelFormatTranslator.ToNetFormat(String ExcelFormat, Boolean forColWidth) at OfficeOpenXml.Style.XmlAccess.ExcelNumberFormatXml.ExcelFormatTranslator..ctor(String format, Int32 numFmtID) at OfficeOpenXml.Style.XmlAccess.ExcelNumberFormatXml.get_FormatTranslator() at OfficeOpenXml.ExcelRangeBase.GetFormattedText(Boolean forWidthCalc) at OfficeOpenXml.ExcelRangeBase.get_TextForWidth() at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth, Double MaximumWidth) at OfficeOpenXml.ExcelRangeBase.AutoFitColumns(Double MinimumWidth) at OfficeOpenXml.ExcelRangeBase.AutoFitColumns() at OfficeOpenXml.ExcelColumn.AutoFit() at SkiptraceAPI.Models.ProcessosRepository.formatExcel(ExcelPackage package, Boolean addValidation) in 

从提到Style.XmlAccess的堆栈跟踪部分来看,看起来像是遇到了OfficeOpenXml实现中的一个真正的错误,触发了单元格样式。

由于在单元格不为null使用Value.ToString()起作用,因此可以使用新添加的空条件语法解决该问题:

 process.Information = sheet.Cells[line, i++].Value?.ToString(); // ^ 

另一个可能的解决方法是使用GetValue<T>

 process.Information = sheet.GetValue<string>(line, i++); 

编辑:它看起来像在第22列的单元格中有一个非数值的样式,其中库期望一个数字string。 库试图parsing一个数字的string,导致exception。 你可以通过改变单元格的格式来解决这个问题,但是实际的修正是修改库来检测格式不匹配而不会引发exception。