ASP.NET中使用Excel匯入資料到資料庫
兩年前大費周章的寫了個匯入程式,現在要用到想直接拿來用。卻找不到了。
於是重新寫了一遍,這裡記錄一下用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
相關推薦
asp.net 操作Excel表資料匯入到SQL Server資料庫
程式碼全部貼出,主要是Excel表中的資料要和資料庫中的資料型別要匹配。 這裡Excel表中的欄位是: 姓名、性別、班級、學號、初始密碼 SQL Server表tb_Users中的欄位是; RealName、 Sex、InClass、Question、Answer &l
Asp.Net中如何將資料匯出到excel
一、定義文件型別、字元編碼 Response.Clear(); Response.Buffer= true; Response.Charset="utf-8";
如何在ASP.Net 中把圖片存入資料庫
介紹 可能有很多的時候,我們急需把圖片存入到資料庫當中。在一些應用程式中,我們可能有一些敏感的資料,由於儲存在檔案系統(file system)中的東西,將很容易被某些使用者盜取,所以這些資料不能存放在檔案系統中。 在這篇文章中,我們將討論怎樣把圖片存入到Sql20
ASP.NET中動態獲取資料使用Highcharts圖表控制元件
<%@ Page Title="" Language="C#" MasterPageFile="~/MyHome/MasterPage.master" AutoEventWireup="true" CodeFile="ryfb.aspx.cs" Inherits="MyHome_tixi_ryfb"%&
ASP.NET中使用Excel匯入資料到資料庫
兩年前大費周章的寫了個匯入程式,現在要用到想直接拿來用。卻找不到了。 於是重新寫了一遍,這裡記錄一下用Excel匯入到資料庫的過程。為下次節省時間... 思路: 1、上傳Excel檔案到伺服器 2、將Excel內容讀取出來 填充到DataTable中 3、將DataTable內容儲存到資料庫內。 (當然還可
在ASP.NET中將Excel檔案中資料匯入資料庫並顯示進度條
在ASP.NET中經常會遇到Excel檔案匯入資料庫的問題,遇到資料量比較大的時候,最好顯示進度條。 進度條設計是參考網上某牛人提供的程式碼,利用JS實現的,謝謝這個大牛了(忘記了當時記錄下他的大名了,:()。具體思路:首先將後臺伺服器上ProgressBar.htm 頁面內
ASP.NET讀取Excel中的資料轉存到資料庫(一)
【問題描述】 近日需要做一些資料倉庫的內容,發現數據庫搭好了以後,所有的資料檔案都是Excel儲存的。然而資料又是及其繁雜,所以在建立好了事實表和維度表以後,準備自己寫一個程式碼將Excel中多維的資料匯入到資料庫中。Excel表的部分資料如下圖所示 所以需要對資料進行處
ASP.NET中 C#訪問資料庫用三種方式顯示資料表
第一種方式:使用DataReader從資料庫中每次提取一條資料,用迴圈遍歷表 下面是我寫的一個例子: &nbs
navicate 匯入Excel 資料到 mysql 資料庫中出現匯入資料失敗,只能顯示錶頭等情況。
是由於當初建庫的時候沒有設定預設的編碼格式,就會導致匯入Excel(含有中文)失敗; 失敗的建庫語句: create database mydatabase; 正確的建庫語句: create database
tp3.2中excel表格資料匯入資料庫
第一步:將壓縮包PHPExcel解壓後放到./ThinkPHP/Library/Vendor目錄下面。 第二步:控制器裡面的方法: public function addActivitydo(){ if (!empty($_FILE
asp.net中開啟Excel上傳檔案,讀取資料的方法
程式碼: /// <summary> /// 開啟Excel檔案 /// </summary> /// <param name="ExcelFileName">檔名</param> private voi
ASP.NET中關於資料匹配和查詢的幾點研究(歡迎大神提供更精妙演算法)
相信下面這種情況在ASP.NET開發中會時常遇到:查詢DataTable_2中的某列資料是否全部出現在DataTable_1中,如果是,則提取部分資料,否則輸出提示。 如果是小資料量,任何的迴圈查詢都無所謂。如果大資料量,那就要講究方法了。本人糾結於這種匹配好久,弄了個測試程式。希望大神能夠
依賴POI實現EXCEL匯入資料並生成javaBean和EXCEL根據資料庫表匯出
首先是excel匯入匯出的工具類程式碼 public class ExportExcel { // 測試123 private ExportExcel() { } /*** * 工作簿 */
ASP.NET MVC NPOI匯入Excel
用NPOI第三方庫匯入匯出Excel的思路:先把你要匯入的Excel上傳到服務端,然後把Excel檔案當做資料庫讀取資料,再儲存到資料庫或者其他操作新建一個專案,下方點選MVC複選框新建一個叫ExcelController控制器新增Index檢視,在裡面寫匯入檔案和表單,注意
在Asp.net 中驗證資料
Asp.net 提供了一系列的驗證控制元件來驗證使用者的輸入。 1. 驗證控制元件總覽 1.1 RequiredFieldValidator 驗證相聯的輸入的控制元件的值是否不同於他的初始值 1.2 CompareValidator 將一個控制
C# Excel匯入資料到資料庫
//專案中用到的一個小例子,拿出來和大家分享 ,需要引用 using System.IO; using System.Data.OleDb; /// <summary> /// Excel資料匯入Datable /// </summ
今天做一個excel匯入資料的功能,用到了NPOI,可是發現excel中日期格式拿到之後格式變了,無法轉換成DateTime型別了
解決方法:DateTime在NPOI中的型別是Numeric ,判斷如果是Numeric 型別的話再用.Net自帶的DateUtil.IsCellDateFormatted(cell)方法判斷是否為DateTime型別,如果2個都成立,取cell的DateCellValue屬
在asp.net中使gridview控制元件內資料居中顯示
再前臺中新增一段<RowStyle HorizontalAlign="Center" /> 即可,或者將gridview控制元件的RowStyle.HorizontalAlign屬性設定為true即可 以上效果會使得控制元件中所有內容都為居中顯示
asp.net mvc DropDownList控制元件 資料庫中取值Select的選項注意事項
//從資料庫中取selectlist的值 前端: @Html.DropDownList("s_group", ViewBag.Values as SelectList, new { @class
asp.net中一個頁面跳轉,後一個頁面操作內容後返回先前頁面,並使得先前頁面資料重新整理
A.aspx 頁面中一個按鈕跳轉到B.aspx頁面,在B.aspx頁面中一個按鈕操作按鈕後,返回上一頁,並重新整理資料。 protected void Page_Load(object sender,