我需要从 Excel 文件中检索数据并将数据插入数据库。我现在尝试检索数据,但我不断收到 HRESULT:0x800A03EC 异常错误。
我的代码:
public void ReadFile()
{
try
{
Excel.Application ep = new Excel.Application();
Excel.Workbook ewb = ep.Workbooks.Open(@"C:/Temp/Copy of AGCO Transport Schedule.xlsx");
Excel.Worksheet ews = ewb.Sheets[1];
Excel.Range range = ews.UsedRange;
int rowCount = range.Rows.Count;
int columnCount = range.Columns.Count;
for (int i = 1; i < rowCount; i++)
{
for (int j = 1; j < columnCount; j++)
{
string str = (string)(range.Cells[i, j] as Excel.Range).Value2;
Console.WriteLine(str);
}
}
}
catch (Exception e)
{
Console.WriteLine("YOLO "+e.Message);
}
}
}
在从此处的用户那里获得上述代码的解决方案后。循环索引应更改为 1 而不是 0。我已经更正了上面的代码。但问题是我只需要从 Excel 中的数据中选择 2 列,所以我继续使用 sql 从 Excel 文件中检索数据。但是这次我不断收到“无法创建文件”错误,当我尝试打开我的连接时会发生这种情况。
我的代码:
public void ReadExcelFile()
{
string connectionString = string.Format(ConfigurationManager.ConnectionStrings["ExcelConnection"].ConnectionString.Replace("'", "\""), "@C:/Temp/Copy.xlsx");
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
string sqlCmd = "SELECT * FROM [Ark1$]";
using (OleDbCommand command = new OleDbCommand(sqlCmd, connection))
{
command.CommandType = System.Data.CommandType.Text;
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.ToString());
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("ERROR in ReadExcelFile() method. Error Message : " + exception.Message);
}
}
}
谁能帮我这个 ?