C#将Excel表格中的数据导入SQL数据库

  private static string _filePath=string.Empty ;
#region Excel导入SQL数据库
  /// <summary>
  /// 获取Excel数据表列表
  /// </summary>
  /// <returns></returns>
  public static ArrayList GetExcelTables()
  {
   //将Excel架构存入数据里
   System.Data.DataTable dt = new System.Data.DataTable();
   ArrayList TablesList=new ArrayList();
   if (File.Exists(FilePath))
   {
    using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet."+
         "OLEDB.4.0;Extended Properties=\"Excel 8.0\";Data Source=" + FilePath))
    {
     try
     {
      conn.Open();
      dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
     }
     catch (Exception exp)
     {
      Log.StrFileName ="查询Excel表单名";
      Log.StrDepartment ="Excel架构存入数据";
      Log.StrDescription =exp.ToString ();
      Log.WriteLog ();
     }

     //获取数据表个数
     int tablecount=dt.Rows.Count;
     for (int i=0;i<tablecount;i=i+2)
     {
      string tablename=dt.Rows[i][2].ToString().Trim().TrimEnd('$');
      if(TablesList.IndexOf(tablename)<0)
      {
       TablesList.Add(tablename);
      }
                       
     }
    }
   }
   return TablesList;
  }

  /// <summary>
  /// 导入Excel数据表至DataTable(第一行作为表头)
  /// </summary>
  /// <returns></returns>
  public static System.Data.DataSet FillDataSet()
  {
   if (!File.Exists(FilePath))
   {
    throw new Exception("Excel文件不存在!");
   }

   ArrayList TableList=new ArrayList();
   TableList = GetExcelTables();
   if(TableList.Count <=0)
   {
     return null;
   }


   System.Data.DataTable table ;
            System.Data .DataSet ds=new DataSet ();
   OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=Excel 8.0");
   try
   {
    if (dbcon.State == ConnectionState.Closed)
    {
     dbcon.Open();
    }
    for(int i=0;i<TableList.Count ;i++)
    {
     string dtname=TableList[i].ToString ();
     try
     {
      OleDbCommand cmd = new OleDbCommand("select * from [" + dtname + "$]", dbcon);
      OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
      table=new DataTable (dtname);
      adapter.Fill(table);
      ds.Tables .Add (table);
     }
     catch (Exception exp)
     {
      Log.StrFileName =dtname;
      Log.StrDepartment ="将Excel表格导入DataSet";
      Log.StrDescription =exp.ToString ();
      Log.WriteLog ();
     }
    }
   }
   finally
   {
    if (dbcon.State == ConnectionState.Open)
    {
     dbcon.Close();
    }
   }
   return ds;
  }
  
  /// <summary>
  /// Excel导入数据库
  /// </summary>
  /// <returns></returns>
  public static DataSet ImportFromExcel()
  {
   return FillDataSet();
  }
 
 #endregion

转载于:https://www.cnblogs.com/SysAlen/archive/2008/07/10/1239955.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C# WinFormExcel数据导入SQL Server数据库的步骤: 1. 需要添加对Microsoft.Office.Interop.Excel和System.Data.SqlClient的引用。 2. 建立一个Windows Form应用程序,并在单上添加一个按钮,用于触发导入Excel数据的过程。 3. 在按钮的Click事件编写代码,打开Excel文件并读取数据。 ```csharp using Excel = Microsoft.Office.Interop.Excel; Excel.Application excelApp = new Excel.Application(); Excel.Workbook workbook = excelApp.Workbooks.Open(@"C:\example.xlsx"); Excel.Worksheet worksheet = workbook.Sheets[1]; int rowsCount = worksheet.UsedRange.Rows.Count; int columnsCount = worksheet.UsedRange.Columns.Count; for (int row = 1; row <= rowsCount; row++) { for (int col = 1; col <= columnsCount; col++) { string cellValue = (worksheet.Cells[row, col] as Excel.Range).Value.ToString(); // Do something with the cell value } } workbook.Close(); excelApp.Quit(); ``` 4. 创建一个SqlConnection对象,用于连接到SQL Server数据库。 ```csharp using System.Data.SqlClient; SqlConnection connection = new SqlConnection("Data Source=serverName;Initial Catalog=databaseName;Integrated Security=True"); connection.Open(); ``` 5. 创建一个SqlCommand对象,用于执行插入语句。 ```csharp SqlCommand command = new SqlCommand("INSERT INTO TableName (Column1, Column2) VALUES (@Value1, @Value2)", connection); command.Parameters.AddWithValue("@Value1", cellValue1); command.Parameters.AddWithValue("@Value2", cellValue2); command.ExecuteNonQuery(); ``` 6. 在循环使用SqlCommand对象插入数据。 7. 关闭SqlConnection对象。 ```csharp connection.Close(); ``` 完成以上步骤后,您的C# WinForm应用程序就能够将Excel数据导入SQL Server数据库了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值