如何将数据从电子表格导入SQL Server?

时间:2012-08-01 05:51:52

标签: c# .net vb.net sql-server-2008 tsql

我应该使用哪些库和DLL将Excel电子表格的数据导入SQL Server 2008?库和dll应该是C#或VB.NET,或者可能是代码片段没问题。

1 个答案:

答案 0 :(得分:0)

这篇文章指导您如何轻松实现

Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function

您无需任何额外的库,只需编写以下代码行即可从Excel中导入数据。

fileName = FileUpload1.ResolveClientUrl(FileUpload1.PostedFile.FileName);
int count = 0;
DataClassesDataContext conLinq = new DataClassesDataContext("Data Source=server name;Initial Catalog=Database Name;Integrated Security=true");
try
{
   DataTable dtExcel = new DataTable();
   string SourceConstr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
   OleDbConnection con = new OleDbConnection(SourceConstr);
   string query = "Select * from [Sheet1$]";
   OleDbDataAdapter data = new OleDbDataAdapter(query, con);
   data.Fill(dtExcel);
   for (int i = 0; i < dtExcel.Rows.Count; i++)
   {
      try
      {
         count += conLinq.ExecuteCommand("insert into table name values(" + dtExcel.Rows[i][0] + "," + dtExcel.Rows[i][1] + ",'" + dtExcel.Rows[i][2] + "',"+dtExcel.Rows[i][3]+")");
      }
      catch (Exception ex)
      {
         continue;
      }
   }
   if (count == dtExcel.Rows.Count)
   {
      <--Success Message-->
   }
   else
   {
      <--Failure Message-->
   }
}
catch (Exception ex)
{
   throw ex;
}
finally
{
}