使用 c# 在 excel 中循环工作表
Loop worksheets in excel using c#
我想在 excel 中循环所有 sheet 并需要将其插入 sql 服务器 table。
我完成了一个编码部分,将单个 sheet excel 插入 sql 服务器 table。
如果 excel 包含更多工作sheets,我想循环这些工作sheets 并需要将其插入 sql 服务器 table.
我已经为循环目的编写了以下代码,但它给出了以下错误;
"ComException was caught" "Retrieving the COM class factory for
component with CLSID {00024500-0000-0000-C000-000000000046} failed due
to the following error: 80040154 Class not registered (Exception from
HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."
这是循环的代码:
string path = @"D:/Projects/sample.xls";
string strConnection = ConfigurationManager.ConnectionStrings["Source"].ToString();
string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\";";
Excel.Application ExcelApp = new Excel.Application();
var Wbook = ExcelApp.Workbooks.Open(path);
foreach (var sheet in Wbook.Worksheets)
{
OleDbCommand cmd = new OleDbCommand("Select [Name], [City], [Address], [Designation] from [" + sheet + "$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "temp1";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
但是在执行行时
var Wbook = ExcelApp.Workbooks.Open(path);
出现上述错误。请建议我。
您需要安装 Microsoft Office 才能像您一样使用互操作程序集。
您必须:
- 安装Excel;
- 或使用第三方组件,例如 EPPlus。
我想在 excel 中循环所有 sheet 并需要将其插入 sql 服务器 table。
我完成了一个编码部分,将单个 sheet excel 插入 sql 服务器 table。
如果 excel 包含更多工作sheets,我想循环这些工作sheets 并需要将其插入 sql 服务器 table.
我已经为循环目的编写了以下代码,但它给出了以下错误;
"ComException was caught" "Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."
这是循环的代码:
string path = @"D:/Projects/sample.xls";
string strConnection = ConfigurationManager.ConnectionStrings["Source"].ToString();
string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\";";
Excel.Application ExcelApp = new Excel.Application();
var Wbook = ExcelApp.Workbooks.Open(path);
foreach (var sheet in Wbook.Worksheets)
{
OleDbCommand cmd = new OleDbCommand("Select [Name], [City], [Address], [Designation] from [" + sheet + "$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "temp1";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
但是在执行行时
var Wbook = ExcelApp.Workbooks.Open(path);
出现上述错误。请建议我。
您需要安装 Microsoft Office 才能像您一样使用互操作程序集。
您必须:
- 安装Excel;
- 或使用第三方组件,例如 EPPlus。