C#读取Excel文件时出现错误“HRESULT中的异常:0X800A03EC”。
代码:
ApplicationClass app = new ApplicationClass();
app.Visible = false;
WorkbookClass w = (WorkbookClass)app.Workbooks.Open(this.XlsFileLb.Text,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
object missing = Type.Missing;
Sheets sheets = w.Worksheets;
Worksheet datasheet = null;
foreach (Worksheet sheet in sheets)
{
if (sheet.Name == "第一页")
{
datasheet = sheet;
break;
}
}
if (null == datasheet)
{
this.MsgLb.Text = "数据文件格式有问题,请检查您的excel文件格式!";
return;
}
Range range = datasheet.get_Range("B3","C184");
System.Array values = (System.Array)range.Formula;
if (values != null)
{
string[] m_A01Info = new string[5];
for (int i = 1; i <= 182; i++)
{
m_A01Info[0] = values.GetValue(i, 1).ToString();
m_A01Info[1] = values.GetValue(i, 2).ToString();
}
}
else
{
this.MsgLb.Text += " 读取数据出错!";
}
app.Quit();
app = null;
原因:读取的Excel文件中某个单元格内容太长,红色部分不对,不能直接用range.Formula将EXCEL的内容直接读取到System.Array 。
解决法方:红色部分替换成如下代码
string[,] values = new string[175,2];
for(int m=0;m<175;m++)
{
values[m,0] = Convert.ToString(datasheet.get_Range("B"+ Convert.ToString(2+m),"B"+ Convert.ToString(2+m)).Text);
values[m,1] = Convert.ToString(datasheet.get_Range("C"+Convert.ToString(2+m),"C"+Convert.ToString(2+m)).Text);
}