標籤:
一:OLEDB方式操作Excel的個人理解
就是把要操作的Excel當作一個資料庫,所有對Excel的操作,就變成了對“資料庫”的操作。那麼這時就需要有一個資料庫的連接字串。
代碼如下:
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strFileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES\"“;
其中的strFileName是指的Excel檔案名稱。
二:讀取Excel檔案,並將內容讀到DataTable中。
代碼如下:
/// <summary> /// 讀取Excel /// </summary> /// <param name="strFileName">Excel檔案名稱</param> /// <param name="fileType"></param> /// <param name="sheetName">Excel中的sheet的名字</param> public static DataTable ExcelReader(string strFileName, string fileType, string sheetName) { string connStr = ""; DataTable _table; connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strFileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES\""; try { using (OleDbConnection conn = new OleDbConnection(connStr)) { conn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}$]", sheetName), conn); DataSet myDataSet = new DataSet(); int i = myCommand.Fill(myDataSet); _table = myDataSet == null ? null : myDataSet.Tables.Count == 0 ? null : myDataSet.Tables[0]; } return _table; } catch (Exception ex) { return null; } }
返回的結果就是一個DataTable.
三:將DataTable儲存為Excel檔案
代碼如下:
/// <summary> /// 從DataTable中讀取資料到excel中 /// </summary> /// <param name="dt">傳入的DataTable</param> public static void DTToExcel(DataTable dt) { string fileName = ((string.IsNullOrEmpty(dt.TableName)) ? "Excel" : dt.TableName) + ".xls"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; GridView GridView1 = new GridView(); GridView1.DataSource = dt; GridView1.DataBind(); StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); GridView1.RenderControl(hw); HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.End(); }
在使用DataTable匯出Excel檔案時,需要先建立DataTable,下面是DataTable的建立小執行個體:
DataTable dt = new DataTable(); string[] strArr = new string[] { "1", "2222", "333333333", "444" }; for (int i = 0; i < strArr.Count(); i++) { dt.Columns.Add(strArr[i]); } for (int i = 0; i < strArr.Count(); i++) { DataRow dr2 = dt.NewRow(); dr2[0] = "總記"; dr2[1] = "11"; dr2[2] = "22"; dr2[3] = "33"; dt.Rows.Add(dr2); }
ASP.NET中的Excel操作(OLEDB方式)