兩年前大費周章的寫了個導入程序,現在要用到想直接拿來用。卻找不到了。
於是重新寫了一遍,這里記錄一下用Excel導入到數據庫的過程。為下次節省時間...
思路:
1、上傳Excel文件到服務器
2、將Excel內容讀取出來 填充到DataTable中
3、將DataTable內容保存到數據庫內。
(當然還可以先校驗后幫到頁面上,讓用戶再次確認要導入的數據。這里我省掉了,只列出詳細的錯誤清單)
so easy。。。
實現:
首先 要准備一個Excel模板。Excel第一行一定要寫入你要導入的字段名稱,名稱可以用漢字,但只要你能和數據庫字段對應起來用程序處理就可以了。
有必要的話 在頁面上寫點說明, 比如哪個字段一定要填寫什么樣的數據。當然程序異常處理還是要的。
1、前台頁面代碼
頁面上就簡單點 放一個上傳控件、一個導入的按鈕。
<div> <p><b>數據導入:</b></p> <div> 選擇文件:<asp:FileUpload ID="fu_excel" runat="server" /> <asp:Button ID="btn_save" runat="server" Text="導入" onclick="btn_save_Click" /><br /> <asp:Label ID="lb_msg" runat="server" Text="" ForeColor="Red"></asp:Label> </div> </div>
2、后台代碼
導入按鈕事件
/// <summary> /// 上傳 保存到數據庫 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btn_save_Click(object sender, EventArgs e) { ExcelUpload(); }
上傳導入的一些方法
/// <summary> /// 文件上傳方法 /// </summary> protected void ExcelUpload() { //存放文件路徑 String filepath = ""; //存放文件擴展名 string fileExtName = ""; //文件名 string mFileName = ""; //服務器上的相對路徑 string mPath = ""; if (fu_excel.PostedFile.FileName != "") { //取得文件路徑 filepath = fu_excel.PostedFile.FileName; //取得文件擴展名 fileExtName = filepath.Substring(filepath.LastIndexOf(".") + 1); //取得服務器上的相對路徑 mPath = this.Request.PhysicalApplicationPath + "UpLoadFiles\\Excel\\"; //取得文件名 mFileName = filepath.Substring(filepath.LastIndexOf("\\") + 1); //保存文件到指定目錄 if (!Directory.Exists(mPath)) { try { Directory.CreateDirectory(mPath); } catch { MessageBox.Show(this.Page, "服務器創建存放目錄失敗"); } } //如果文件已經存在則刪除原來的文件 if (File.Exists(mPath + mFileName)) { try { File.Delete(mPath + mFileName); } catch { MessageBox.Show(this.Page, "服務器上存在相同文件,刪除失敗。"); } } #region 判斷文件擴展名 //判斷上傳文件格式 Boolean fileOK = false; if (fu_excel.HasFile) { String fileExtension = System.IO.Path.GetExtension(fu_excel.FileName).ToLower(); String[] allowedExtensions = { ".xls" }; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } #endregion #region 判斷文件是否上傳成功 //判斷文件是否上傳成功 bool fileUpOK = false; if (fileOK) { try { //文件上傳到服務器 fu_excel.PostedFile.SaveAs(mPath + mFileName); fileUpOK = true; } catch { MessageBox.Show(this.Page,"文件上傳失敗!請確認文件內容格式符合要求!"); } } else { MessageBox.Show(this.Page,"上傳文件的格式錯誤,應為.xls格式!"); } #endregion #region 將Excel填充到數據集 //將Excel填充到數據集 if (fileUpOK) { System.Data.DataTable dt_User = new System.Data.DataTable(); try { //獲取Excel表中的內容 dt_User = GetList(mPath + mFileName); if (dt_User==null) { MessageBox.Show(this.Page, "獲取Excel內容失敗!"); return; } } catch { MessageBox.Show(this.Page,"獲取Excel內容失敗!"); } int rowNum = 0; try { rowNum = dt_User.Rows.Count; } catch { MessageBox.Show(this.Page,"Excel表獲取失敗!"); } if (rowNum == 0) { MessageBox.Show(this.Page,"Excel為空表,無數據!"); } else { //數據保存 SaveToDataBase(dt_User); } } #endregion } } #region 讀取Excel表數據 /// <summary> /// 根據Excel文件路徑讀取Excel表中第一個表的內容 /// </summary> /// <param name="FilePath">Excel文件的物理路徑</param> /// <returns>DataSet</returns> public System.Data.DataTable GetList(string FilePath) { string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0;"; string strSql = string.Empty; //string workSheetName = Get_FistWorkBookName(FilePath);
//第一個工作表的名稱。考慮到穩定性,就直接寫死了。 string workSheetName = "Sheet1"; if (workSheetName != "") { strSql = "select * from [" + workSheetName + "$]"; try { OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); OleDbDataAdapter myCommand = null; myCommand = new OleDbDataAdapter(strSql, connectionString); System.Data.DataTable dt = new System.Data.DataTable(); myCommand.Fill(dt); conn.Close(); conn.Dispose(); return dt; } catch (Exception) { return null; } } else { return null; } } /// <summary> /// 根據EXCEL文件路徑獲取EXCEL第一個工作薄的表名 /// 缺點:需要打開excel占用進程,暫不使用此方法 /// 優點:更靈活,可以隨意更改表名 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public string Get_FistWorkBookName(string fileName) { Application app = new ApplicationClass(); Workbook workBook = app.Workbooks.Add(Type.Missing); ; Worksheet workSheet = (Worksheet)workBook.Sheets.get_Item(1); string rev = string.Empty; if (!File.Exists(fileName)) throw new Exception("指定路徑的Excel文件不存在!"); Workbook tmpworkBook; Worksheet tmpworkSheet; try { object missing = System.Reflection.Missing.Value; //打開一個WorkBook tmpworkBook = app.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, missing); // tmpworkSheet = (Worksheet) workBook.Sheets.get_Item ( 1 ); app.Visible = false; tmpworkSheet = (Worksheet)tmpworkBook.Worksheets[1]; rev = tmpworkSheet.Name; } catch { rev = ""; } finally { tmpworkSheet = null; tmpworkBook = null; this.Dispose(); } return rev; } #endregion
#region 將數據保存到數據庫 /// <summary> /// 將數據保存到數據庫 /// </summary> /// <param name="dt_user"></param> protected void SaveToDataBase(System.Data.DataTable dt_user) { string strMsg = ""; lb_msg.Text = ""; //創建事務s SqlTransaction trans_user = null; //打開數據連接 SqlConnection con = new SqlConnection(PubConstant.ConnectionString); con.Open(); //事務開始 trans_user = con.BeginTransaction(); try { // 導入的話能用事務還是用事務處理吧 //事務提交 trans_user.Commit(); //flagOk = true; MessageBox.Show(this.Page, "數據導入成功!"); } catch (Exception ex) { trans_user.Rollback(); MessageBox.Show(this.Page, "數據導入失敗!" + ex.ToString().Substring(0, ex.ToString().IndexOf("。") + 1) + " <br />請檢查文件內容后重新導入!"); } finally { con.Close(); trans_user = null; lb_msg.Text = strMsg; } } #endregion