C#自定義導(dǎo)出數(shù)據(jù)到Excel的類實(shí)例
本文實(shí)例講述了C#自定義導(dǎo)出數(shù)據(jù)到Excel的類。分享給大家供大家參考。具體如下:
C#自定義Excel操作類,可以用于將DataTable導(dǎo)出到Excel文件,從Excel文件讀取數(shù)據(jù)。
using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DotNet.Utilities { /// <summary> /// Excel操作類 /// </summary> /// Microsoft Excel 11.0 Object Library public class ExcelHelper { #region 數(shù)據(jù)導(dǎo)出至Excel文件 /// </summary> /// 導(dǎo)出Excel文件,自動(dòng)返回可下載的文件流 /// </summary> public static void DataTable1Excel(System.Data.DataTable dtData) { GridView gvExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); curContext.Response.Charset = "utf-8"; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); gvExport = new GridView(); gvExport.DataSource = dtData.DefaultView; gvExport.AllowPaging = false; gvExport.DataBind(); gvExport.RenderControl(htmlWriter); curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\"/>" + strWriter.ToString()); curContext.Response.End(); } } /// <summary> /// 導(dǎo)出Excel文件,轉(zhuǎn)換為可讀模式 /// </summary> public static void DataTable2Excel(System.Data.DataTable dtData) { DataGrid dgExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = ""; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); dgExport = new DataGrid(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } } /// <summary> /// 導(dǎo)出Excel文件,并自定義文件名 /// </summary> public static void DataTable3Excel(System.Data.DataTable dtData, String FileName) { GridView dgExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); curContext.Response.ContentType = "application nd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = "GB2312"; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); dgExport = new GridView(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } } /// <summary> /// 將數(shù)據(jù)導(dǎo)出至Excel文件 /// </summary> /// <param name="Table">DataTable對象</param> /// <param name="ExcelFilePath">Excel文件路徑</param> public static bool OutputToExcel(DataTable Table, string ExcelFilePath) { if (File.Exists(ExcelFilePath)) { throw new Exception("該文件已經(jīng)存在!"); } if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table")) { Table.TableName = "Sheet1"; } //數(shù)據(jù)表的列數(shù) int ColCount = Table.Columns.Count; //用于記數(shù),實(shí)例化參數(shù)時(shí)的序號 int i = 0; //創(chuàng)建參數(shù) OleDbParameter[] para = new OleDbParameter[ColCount]; //創(chuàng)建表結(jié)構(gòu)的SQL語句 string TableStructStr = @"Create Table " + Table.TableName + "("; //連接字符串 string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(connString); //創(chuàng)建表結(jié)構(gòu) OleDbCommand objCmd = new OleDbCommand(); //數(shù)據(jù)類型集合 ArrayList DataTypeList = new ArrayList(); DataTypeList.Add("System.Decimal"); DataTypeList.Add("System.Double"); DataTypeList.Add("System.Int16"); DataTypeList.Add("System.Int32"); DataTypeList.Add("System.Int64"); DataTypeList.Add("System.Single"); //遍歷數(shù)據(jù)表的所有列,用于創(chuàng)建表結(jié)構(gòu) foreach (DataColumn col in Table.Columns) { //如果列屬于數(shù)字列,則設(shè)置該列的數(shù)據(jù)類型為double if (DataTypeList.IndexOf(col.DataType.ToString()) >= 0) { para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.Double); objCmd.Parameters.Add(para[i]); //如果是最后一列 if (i + 1 == ColCount) { TableStructStr += col.ColumnName + " double)"; } else { TableStructStr += col.ColumnName + " double,"; } } else { para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.VarChar); objCmd.Parameters.Add(para[i]); //如果是最后一列 if (i + 1 == ColCount) { TableStructStr += col.ColumnName + " varchar)"; } else { TableStructStr += col.ColumnName + " varchar,"; } } i++; } //創(chuàng)建Excel文件及文件結(jié)構(gòu) try { objCmd.Connection = objConn; objCmd.CommandText = TableStructStr; if (objConn.State == ConnectionState.Closed) { objConn.Open(); } objCmd.ExecuteNonQuery(); } catch (Exception exp) { throw exp; } //插入記錄的SQL語句 string InsertSql_1 = "Insert into " + Table.TableName + " ("; string InsertSql_2 = " Values ("; string InsertSql = ""; //遍歷所有列,用于插入記錄,在此創(chuàng)建插入記錄的SQL語句 for (int colID = 0; colID < ColCount; colID++) { if (colID + 1 == ColCount) //最后一列 { InsertSql_1 += Table.Columns[colID].ColumnName + ")"; InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ")"; } else { InsertSql_1 += Table.Columns[colID].ColumnName + ","; InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ","; } } InsertSql = InsertSql_1 + InsertSql_2; //遍歷數(shù)據(jù)表的所有數(shù)據(jù)行 for (int rowID = 0; rowID < Table.Rows.Count; rowID++) { for (int colID = 0; colID < ColCount; colID++) { if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "") { para[colID].Value = 0; } else { para[colID].Value = Table.Rows[rowID][colID].ToString().Trim(); } } try { objCmd.CommandText = InsertSql; objCmd.ExecuteNonQuery(); } catch (Exception exp) { string str = exp.Message; } } try { if (objConn.State == ConnectionState.Open) { objConn.Close(); } } catch (Exception exp) { throw exp; } return true; } /// <summary> /// 將數(shù)據(jù)導(dǎo)出至Excel文件 /// </summary> /// <param name="Table">DataTable對象</param> /// <param name="Columns">要導(dǎo)出的數(shù)據(jù)列集合</param> /// <param name="ExcelFilePath">Excel文件路徑</param> public static bool OutputToExcel(DataTable Table, ArrayList Columns, string ExcelFilePath) { if (File.Exists(ExcelFilePath)) { throw new Exception("該文件已經(jīng)存在!"); } //如果數(shù)據(jù)列數(shù)大于表的列數(shù),取數(shù)據(jù)表的所有列 if (Columns.Count > Table.Columns.Count) { for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++) { Columns.RemoveAt(s); //移除數(shù)據(jù)表列數(shù)后的所有列 } } //遍歷所有的數(shù)據(jù)列,如果有數(shù)據(jù)列的數(shù)據(jù)類型不是 DataColumn,則將它移除 DataColumn column = new DataColumn(); for (int j = 0; j < Columns.Count; j++) { try { column = (DataColumn)Columns[j]; } catch (Exception) { Columns.RemoveAt(j); } } if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table")) { Table.TableName = "Sheet1"; } //數(shù)據(jù)表的列數(shù) int ColCount = Columns.Count; //創(chuàng)建參數(shù) OleDbParameter[] para = new OleDbParameter[ColCount]; //創(chuàng)建表結(jié)構(gòu)的SQL語句 string TableStructStr = @"Create Table " + Table.TableName + "("; //連接字符串 string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(connString); //創(chuàng)建表結(jié)構(gòu) OleDbCommand objCmd = new OleDbCommand(); //數(shù)據(jù)類型集合 ArrayList DataTypeList = new ArrayList(); DataTypeList.Add("System.Decimal"); DataTypeList.Add("System.Double"); DataTypeList.Add("System.Int16"); DataTypeList.Add("System.Int32"); DataTypeList.Add("System.Int64"); DataTypeList.Add("System.Single"); DataColumn col = new DataColumn(); //遍歷數(shù)據(jù)表的所有列,用于創(chuàng)建表結(jié)構(gòu) for (int k = 0; k < ColCount; k++) { col = (DataColumn)Columns[k]; //列的數(shù)據(jù)類型是數(shù)字型 if (DataTypeList.IndexOf(col.DataType.ToString().Trim()) >= 0) { para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.Double); objCmd.Parameters.Add(para[k]); //如果是最后一列 if (k + 1 == ColCount) { TableStructStr += col.Caption.Trim() + " Double)"; } else { TableStructStr += col.Caption.Trim() + " Double,"; } } else { para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.VarChar); objCmd.Parameters.Add(para[k]); //如果是最后一列 if (k + 1 == ColCount) { TableStructStr += col.Caption.Trim() + " VarChar)"; } else { TableStructStr += col.Caption.Trim() + " VarChar,"; } } } //創(chuàng)建Excel文件及文件結(jié)構(gòu) try { objCmd.Connection = objConn; objCmd.CommandText = TableStructStr; if (objConn.State == ConnectionState.Closed) { objConn.Open(); } objCmd.ExecuteNonQuery(); } catch (Exception exp) { throw exp; } //插入記錄的SQL語句 string InsertSql_1 = "Insert into " + Table.TableName + " ("; string InsertSql_2 = " Values ("; string InsertSql = ""; //遍歷所有列,用于插入記錄,在此創(chuàng)建插入記錄的SQL語句 for (int colID = 0; colID < ColCount; colID++) { if (colID + 1 == ColCount) //最后一列 { InsertSql_1 += Columns[colID].ToString().Trim() + ")"; InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ")"; } else { InsertSql_1 += Columns[colID].ToString().Trim() + ","; InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ","; } } InsertSql = InsertSql_1 + InsertSql_2; //遍歷數(shù)據(jù)表的所有數(shù)據(jù)行 DataColumn DataCol = new DataColumn(); for (int rowID = 0; rowID < Table.Rows.Count; rowID++) { for (int colID = 0; colID < ColCount; colID++) { //因?yàn)榱胁贿B續(xù),所以在取得單元格時(shí)不能用行列編號,列需得用列的名稱 DataCol = (DataColumn)Columns[colID]; if (para[colID].DbType == DbType.Double && Table.Rows[rowID][DataCol.Caption].ToString().Trim() == "") { para[colID].Value = 0; } else { para[colID].Value = Table.Rows[rowID][DataCol.Caption].ToString().Trim(); } } try { objCmd.CommandText = InsertSql; objCmd.ExecuteNonQuery(); } catch (Exception exp) { string str = exp.Message; } } try { if (objConn.State == ConnectionState.Open) { objConn.Close(); } } catch (Exception exp) { throw exp; } return true; } #endregion /// <summary> /// 獲取Excel文件數(shù)據(jù)表列表 /// </summary> public static ArrayList GetExcelTables(string ExcelFileName) { DataTable dt = new DataTable(); ArrayList TablesList = new ArrayList(); if (File.Exists(ExcelFileName)) { using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName)) { try { conn.Open(); dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); } catch (Exception exp) { throw exp; } //獲取數(shù)據(jù)表個(gè)數(shù) int tablecount = dt.Rows.Count; for (int i = 0; i < tablecount; i++) { string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$'); if (TablesList.IndexOf(tablename) < 0) { TablesList.Add(tablename); } } } } return TablesList; } /// <summary> /// 將Excel文件導(dǎo)出至DataTable(第一行作為表頭) /// </summary> /// <param name="ExcelFilePath">Excel文件路徑</param> /// <param name="TableName">數(shù)據(jù)表名,如果數(shù)據(jù)表名錯(cuò)誤,默認(rèn)為第一個(gè)數(shù)據(jù)表名</param> public static DataTable InputFromExcel(string ExcelFilePath, string TableName) { if (!File.Exists(ExcelFilePath)) { throw new Exception("Excel文件不存在!"); } //如果數(shù)據(jù)表名不存在,則數(shù)據(jù)表名為Excel文件的第一個(gè)數(shù)據(jù)表 ArrayList TableList = new ArrayList(); TableList = GetExcelTables(ExcelFilePath); if (TableName.IndexOf(TableName) < 0) { TableName = TableList[0].ToString().Trim(); } DataTable table = new DataTable(); OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0"); OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon); OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); try { if (dbcon.State == ConnectionState.Closed) { dbcon.Open(); } adapter.Fill(table); } catch (Exception exp) { throw exp; } finally { if (dbcon.State == ConnectionState.Open) { dbcon.Close(); } } return table; } /// <summary> /// 獲取Excel文件指定數(shù)據(jù)表的數(shù)據(jù)列表 /// </summary> /// <param name="ExcelFileName">Excel文件名</param> /// <param name="TableName">數(shù)據(jù)表名</param> public static ArrayList GetExcelTableColumns(string ExcelFileName, string TableName) { DataTable dt = new DataTable(); ArrayList ColsList = new ArrayList(); if (File.Exists(ExcelFileName)) { using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName)) { conn.Open(); dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, TableName, null }); //獲取列個(gè)數(shù) int colcount = dt.Rows.Count; for (int i = 0; i < colcount; i++) { string colname = dt.Rows[i]["Column_Name"].ToString().Trim(); ColsList.Add(colname); } } } return ColsList; } } }
希望本文所述對大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C#調(diào)用7z實(shí)現(xiàn)文件的壓縮與解壓
這篇文章主要介紹了C#調(diào)用7z實(shí)現(xiàn)文件的壓縮與解壓,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2020-12-12采用C#實(shí)現(xiàn)軟件自動(dòng)更新的方法
這篇文章主要介紹了采用C#實(shí)現(xiàn)軟件自動(dòng)更新的方法,非常實(shí)用的功能,需要的朋友可以參考下2014-08-08Unity學(xué)習(xí)之FSM有限狀態(tài)機(jī)
這篇文章主要介紹了Unity學(xué)習(xí)之FSM有限狀態(tài)機(jī),通過詳細(xì)的代碼案例來進(jìn)行解析說明,希望這篇文章對你有所幫助2021-06-06C#中遍歷DataSet數(shù)據(jù)集對象實(shí)例
這篇文章主要介紹了C#中遍歷DataSet數(shù)據(jù)集對象實(shí)例,經(jīng)常忘記如何操作DataSet,這里記下來并分享,讓需要的朋友可以參考下2014-08-08C#使用正則表達(dá)式實(shí)現(xiàn)漢字轉(zhuǎn)拼音
這篇文章主要為大家詳細(xì)介紹了C#如何使用正則表達(dá)式實(shí)現(xiàn)漢字轉(zhuǎn)拼音的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01