網上有很多這種方法,本人只是針對自己的系統來實現的
//匯入excel表
private void ImportTSMenu_Click(object sender, EventArgs e)
{
OpenFileDialog openFD = new OpenFileDialog();
openFD.Filter = "Excel檔案|*.xls";
if (openFD.ShowDialog(this.Owner) == DialogResult.OK)
{
string strFilename = openFD.FileName;
if (!File.Exists(strFilename))
{
MessageBox.Show("檔案不存在,請重新選擇檔案!");
return;
}
//string strConn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + strFilename + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strFilename + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
//關於OleDB連線Excel的Extended Properties(擴充套件屬性)HDR=YES; IMEX=2
//HDR=Yes,這代表第一行是標題,不做為資料使用 ,如果用HDR=NO,則表示第一行不是標題,做為資料來使用。系統預設的是YES
//引數Excel 8.0 對於Excel 97以上到2003版本都用Excel 8.0,2007或2010的都用Extended Properties=Excel 12.0
//IMEX 有三種模式:
//當 IMEX=0 時為“匯出模式”,這個模式開啟的 Excel 檔案只能用來做“寫入”用途。
//當 IMEX=1 時為“匯入模式”,這個模式開啟的 Excel 檔案只能用來做“讀取”用途。
//當 IMEX=2 時為“連結模式”,這個模式開啟的 Excel 檔案可同時支援“讀取”與“寫入”用途。
OleDbDataAdapter oldAda = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
DataSet ds = new DataSet();
oldAda.Fill(ds); //C#匯入execl 找不到可安裝的 ISAM,如果是Office2003版本
//string strConn = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + excelFile + ";Extended Properties=‘Excel 8.0; HDR=YES; IMEX=1’";
//如果是2007以上
//string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;data source=" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
DataTable dt = ds.Tables[];
InsertData(dt);
//this.FTLucky_Load(sender, e);
GetData();
}
}
下面有for迴圈一條條插入到資料庫可能效率不高,應該有批量匯入的,好像sql是用SqlBulkCopy,至於access的話,由於時間緊,且要求不高,就暫時用for代替了
#region 3、將excel資料插入到資料庫
/// <summary>
/// 將DataTable的資料插入到資料庫
/// </summary>
/// <param name="dt">excel資料</param>
private void InsertData(DataTable dt)
{
try
{
oledCon = sqlHelper.OledCon();
oledCon.Open();
string strInsert = "";
for (int i = ; i < dt.Rows.Count; i++)
{
strInsert = "insert into Information([UserName],[Phone]) values('" + dt.Rows[i][] + "','" + dt.Rows[i][] + "')";
oledCmd = new OleDbCommand(strInsert, oledCon);
oledCmd.ExecuteNonQuery();
}
MessageBox.Show("匯入成功!");
}
catch (Exception ex)
{
MessageBox.Show("匯入出錯,原因:" + ex.Message.ToString());
}
finally
{
oledCon.Dispose();
oledCon.Close();
}
}
#endregion