程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> C# 或Asp.Net 將excel表格導入數據庫

C# 或Asp.Net 將excel表格導入數據庫

編輯:關於SqlServer

環境:c#.2005+Access+ Sql 

一、把DataTable插入數據庫
public static void DataTableToDB()
{
      string _strExcelFileName = @"D:\example.xls";
      DataTable dtExcel = ExcelToDataTable(_strExcelFileName,"Sheet1");
      for (int i = 0; i < dtExcel.Rows.Count; i++)
      {
           InsertDataToAccess(dtExcel.Rows[i][0].ToString(), float.Parse(dtExcel.Rows[i][1].ToString()));
      }
}

二、把Excel數據讀入DataTable
public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
      string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" +"Extended PropertIEs=Excel 5.0;";
      string strExcel = string.Format("select * from [{0}$]", strSheetName);
      DataSet ds = new DataSet();

      using (OleDbConnection conn = new OleDbConnection(strConn))
      {
           conn.Open();
           OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
           adapter.Fill(ds, strSheetName);
           conn.Close();
      }

      return ds.Tables[strSheetName];
}

三、向Access數據庫表插入數據
public static void InsertDataToAccess(string _strPara,float _fPara)
{
      OleDbConnection oleDbConn = new OleDbConnection();
      oleDbConn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ExcelData.mdb;User Id=admin;PassWord=;";
      oleDbConn.Open();

      string strInsertString = "INSERT INTO tb_ExcelData (strCollumn1,fCollumn2) VALUES (@strCollumn1,@fCollumn2)";
      OleDbCommand oComm = new OleDbCommand(strInsertString, oleDbConn);
      oComm.Parameters.Add("@strCollumn1", OleDbType.Char , 50);
      oComm.Parameters["@strCollumn1"].Value = _strPara;
      oComm.Parameters.Add("@fCollumn2", OleDbType.Double);
      oComm.Parameters["@fCollumn2"].Value = _fPara;
     
      ocomm.ExecuteNonQuery();
      oleDbConn.Close();
}

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved