首页 > 代码库 > ExcelHelper
ExcelHelper
using System;using System.Collections.Generic;using System.Web;using System.Web.UI.WebControls;using System.IO;using System.Data;using System.Data.OleDb;using System.Collections;using System.Web.UI;namespace Mujinsoft.CM.Core.Helpers{ public static class ExcelHelper { /// <summary> /// 获取Excel数据表列表 /// </summary> /// <param name="ExcelFileName"></param> /// <returns></returns> public static ArrayList GetExcelTables(string ExcelFileName) { //将Excel架构存入数据里 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; } //获取数据表个数 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文件数据表的数据列列表 /// </summary> /// <param name="ExcelFileName">Excel文件名</param> /// <param name="TableName">数据表名</param> /// <returns></returns> public static ArrayList GetExcelTableColumns(string ExcelFileName, string TableName) { //将Excel架构存入数据里 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 }); //获取列个数 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; } /// <summary> /// 获取指定Excel文件数据表的数据列列表 /// </summary> /// <param name="ExcelFileName">Excel文件名</param> /// <param name="TableName">数据表名</param> /// <returns></returns> public static DataTable GetExcelTable(string ExcelFileName, string TableName) { //将Excel架构存入数据里 DataTable dt = new DataTable(); 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 }); } } return dt; } /// <summary> /// 将数据导出至Excel /// </summary> /// <param name="Table">DataTable对象</param> /// <param name="ExcelFilePath">Excel文件路径</param> /// <returns></returns> public static bool OutputToExcel(DataTable Table, string ExcelFilePath) { if (File.Exists(ExcelFilePath)) { throw new Exception("该文件已经存在!"); } if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table")) { Table.TableName = "Sheet1"; } //数据表的列数 int ColCount = Table.Columns.Count; //用于记数,实例化参数时的序号 int i = 0; //创建参数 OleDbParameter[] para = new OleDbParameter[ColCount]; //创建表结构的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); //创建表结构 OleDbCommand objCmd = new OleDbCommand(); //数据类型集合 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"); //遍历数据表的所有列,用于创建表结构 foreach (DataColumn col in Table.Columns) { //如果列属于数字列,则设置该列的数据类型为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++; } //创建Excel文件及文件结构 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 = ""; //遍历所有列,用于插入记录,在此创建插入记录的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; //遍历数据表的所有数据行 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> /// 将数据导出至Excel /// </summary> /// <param name="Table">DataTable对象</param> /// <param name="Columns">要导出的数据列集合</param> /// <param name="ExcelFilePath">Excel文件路径</param> /// <returns></returns> public static bool OutputToExcel(DataTable Table, ArrayList Columns, string ExcelFilePath) { if (File.Exists(ExcelFilePath)) { throw new Exception("该文件已经存在!"); } //如果数据列数大于表的列数,取数据表的所有列 if (Columns.Count > Table.Columns.Count) { for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++) { Columns.RemoveAt(s); //移除数据表列数后的所有列 } } //遍历所有的数据列,如果有数据列的数据类型不是 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"; } //数据表的列数 int ColCount = Columns.Count; //用于记数,实例化参数时的序号 //int i = 0; //创建参数 OleDbParameter[] para = new OleDbParameter[ColCount]; //创建表结构的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); //创建表结构 OleDbCommand objCmd = new OleDbCommand(); //数据类型集合 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(); //遍历数据表的所有列,用于创建表结构 for (int k = 0; k < ColCount; k++) { col = (DataColumn)Columns[k]; //列的数据类型是数字型 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,"; } } } //创建Excel文件及文件结构 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 = ""; //遍历所有列,用于插入记录,在此创建插入记录的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; //遍历数据表的所有数据行 DataColumn DataCol = new DataColumn(); for (int rowID = 0; rowID < Table.Rows.Count; rowID++) { for (int colID = 0; colID < ColCount; colID++) { //因为列不连续,所以在取得单元格时不能用行列编号,列需得用列的名称 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; } /// <summary> /// 导入Excel数据表至DataTable(第一行作为表头) /// </summary> /// <param name="ExcelFilePath">Excel文件路径</param> /// <param name="TableName">数据表名,如果数据表名错误,默认为第一个数据表名</param> /// <returns></returns> public static DataTable InputFromExcel(string ExcelFilePath, string TableName) { if (!File.Exists(ExcelFilePath)) { throw new Exception("Excel文件不存在!"); } //如果数据表名不存在,数据表名为Excel文件的第一个数据表 ArrayList TableList = new ArrayList(); TableList = ExcelHelper.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; } #region 调用前注意事项 //必须将页面的EnableEventValidation属性设为false //必须履盖页面的VerifyRenderingInServerForm方法 #endregion #region GridView导出到Excel静态方法 public static void ToExcelGridView(GridView gdView, string FileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>"); HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文 HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 gdView.EnableViewState = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); gdView.RenderControl(oHtmlTextWriter); HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); } #endregion #region FormView导出到Excel静态方法 public static void ToExcelFormView(FormView formView) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "GB2312"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls"); HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");//设置输出流为简体中文 HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 formView.EnableViewState = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); formView.RenderControl(oHtmlTextWriter); HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); } #endregion public static void ToExcelDataSet(DataSet ds, string FileName) { GridView gdView = new GridView(); gdView.DataSource = ds.Tables[0].DefaultView; gdView.DataBind(); ToExcelGridView(gdView, FileName); } public static void ToExcelList<T>(List<T> list, string FileName) { GridView gdView = new GridView(); gdView.DataSource = DataHelper.ToDataTable<T>(list); gdView.DataBind(); ToExcelGridView(gdView, FileName); } public static void ToExcelDataSet<T>(IList<T> ds, string FileName) { GridView gdView = new GridView(); gdView.DataSource = ds; gdView.DataBind(); ToExcelGridView(gdView, FileName); } #region GridView导出到Excel静态方法 public static void ToExcelRepeater(Repeater gdView, string FileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>"); HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文 HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 gdView.EnableViewState = false; System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); gdView.RenderControl(oHtmlTextWriter); HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.End(); } #endregion #region 将数据导入Excel /// <summary> /// 获取Excel文件数据表列表 /// </summary> public static ArrayList FromExcel(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; } //获取数据表个数 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文件导出至DataTable(第一行作为表头) /// </summary> /// <param name="ExcelFilePath">Excel文件路径</param> /// <param name="TableName">数据表名,如果数据表名错误,默认为第一个数据表名</param> public static DataTable FromExcel(string ExcelFilePath, string TableName) { if (!File.Exists(ExcelFilePath)) { throw new Exception("Excel文件不存在!"); } //如果数据表名不存在,则数据表名为Excel文件的第一个数据表 ArrayList TableList = new ArrayList(); TableList = FromExcel(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; } #endregion public static DataTable GetExcelToDataTableBySheet(string FileFullPath, string SheetName) { string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + FileFullPath + ";Extended Properties=‘Excel 8.0; HDR=NO; IMEX=1‘"; //此连接只能操作Excel2007之前(.xls)文件 //string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + FileFullPath + ";Extended Properties=‘Excel 12.0; HDR=NO; IMEX=1‘"; //此连接可以操作.xls与.xlsx文件 OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataSet ds = new DataSet(); OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}$]", SheetName), conn); //("select * from [Sheet1$]", conn); odda.Fill(ds, SheetName); conn.Close(); return ds.Tables[0]; } #region 导出Excel文件,自动返回可下载的文件流 /// 导出Excel文件,自动返回可下载的文件流 public static void DataTableExcel(System.Data.DataTable dtData, string FileName) { HttpContext.Current.Response.Clear(); 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.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>"); 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 = "utf-8"; 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(); } } #endregion }}
ExcelHelper
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。