读取 ExcelWorksheet 时出现 C# ArgumentOutOfRangeException

标签 c# excel outofrangeexception

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

我正在这样阅读 process.Information = sheet.Cells[line, i++].Text;。在这一行 i = 22sheet.Dimension.Column = 28sheet #columns

i value 当我调试和枚举集合时,我看到在 .Text 方法上抛出了异常,而 .Value 方法显示了正确的值。

collection enumerated

根据异常堆栈跟踪,异常是由 System.Text.StringBuilder.Insert()方法

trace

---- 编辑---- 在接受答案后,我意识到问题不仅仅在于阅读。我用一个额外的列(导入成功或不成功)回复同一个文件,当我进行工作表格式化时,我再次遇到同样的错误,这都是由于方法 System.Text.StringBuilder.Insert() 造成的。我正在尝试自动调整列 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 时遇到了真正的错误由相关单元格的样式触发。

自从使用 Value.ToString()当单元格不是 null 时为您工作,您可以使用新添加的 null 条件 语法解决此错误:

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

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

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

编辑:第 22 列的单元格中似乎有一个样式,该样式具有非数字值,而库需要一个数字字符串。库尝试解析数字字符串,导致异常。您可以通过更改单元格的格式来解决此问题,但实际的解决方法是修改库以检测格式不匹配而不会引发异常。

关于读取 ExcelWorksheet 时出现 C# ArgumentOutOfRangeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38221998/

相关文章:

c# - 中继访问被拒绝 5.7.1

c# - 通过 AJAX 在 Controller 操作中接收空值

excel - 可以显示 n 和所有正的 n-x 递减数吗?

c++ - 为什么我会在这里得到 out_of_range 异常?

android - 多点触控指针索引超出范围

c# - 从 HttpStatusCode 生成 int 值

c# - 使用 HttpClient PostAsJsonAsync 在 ASP.NET Core 中发送 HTTP POST 消息

c++ - 在 vector 的 vector 上捕获 out_of_range

excel - 我的 excel 文件是德国(德语)格式,想更改为英语(英国)格式

vba - 删除值为零的数据标签然后重置 - VBA