Excel操作帮助类

    /// <summary>

    /// Excel操作类

    /// </summary>

    /// Microsoft Excel 11.0 Object Library

    /// 

    public class ExcelHelper
    {
        #region 数据导出至Excel文件
        /// </summary> 

        /// 导出Excel文件,自动返回可下载的文件流 

        /// </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>

        /// 导出Excel文件,转换为可读模式

        /// </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>

        /// 导出Excel文件,并自定义文件名

        /// </summary>

        public static void DataTable3Excel(System.Data.DataTable dtData, String FileName, List<string[]> columnList)
        {
            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.Default;
                curContext.Response.Charset = "gb2312";
                strWriter = new StringWriter();
                htmlWriter = new HtmlTextWriter(strWriter);

                dgExport = new GridView();
                dgExport.AutoGenerateColumns = false;

                /*--------创建列-----------*/
                columnList.ForEach((arr) =>
                {
                    BoundField boundField = new BoundField();
                    boundField.HtmlEncode = true;
                    boundField.DataField = arr[0];
                    boundField.HeaderText = arr[1];

                    dgExport.Columns.Add(boundField);
                });

                dgExport.DataSource = dtData.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }

        /// <summary>

        /// 将数据导出至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("该文件已经存在!");
            }

            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>

        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;

            //创建参数

            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> 

        /// dtData是要导出为Excel的DataTable,FileName是要导出的Excel文件名(不加.xls) 

        /// </summary> 

        /// <param name="dtData"></param> 

        /// <param name="FileName"></param> 

        public static void DataTable3Excel(System.Data.DataTable dtData, String FileName)
        {
            System.Web.UI.WebControls.GridView dgExport = null;
            //当前对话 

            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            //IO用于导出并返回excel文件 

            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                //设置编码和附件格式 

                //System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);//作用是防止中文文件名乱码 

                curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                curContext.Response.ContentType = "application nd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                curContext.Response.Charset = "GB2312";

                //导出Excel文件 

                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView 

                dgExport = new System.Web.UI.WebControls.GridView();
                dgExport.DataSource = dtData.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();

                //下载到客户端 

                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }


        #endregion

        /// <summary>

        /// 获取Excel文件数据表列表

        /// </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.Ace.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES; IMEX=1';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 InputFromExcel(string ExcelFilePath, string TableName)
        {
            if (!File.Exists(ExcelFilePath))
            {
                throw new Exception("Excel文件不存在!");
            }

            //如果数据表名不存在,则数据表名为Excel文件的第一个数据表

            ArrayList TableList = new ArrayList();
            TableList = GetExcelTables(ExcelFilePath);


            if (TableName.IndexOf(TableList[0].ToString().Trim()) < 0)
            {

                TableName = TableList[0].ToString().Trim();
            }

                DataTable table = new DataTable();
                OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties='Excel 12.0;HDR=YES; IMEX=1'");
                //OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon);

                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文件指定数据表的数据列表

        /// </summary>

        /// <param name="ExcelFileName">Excel文件名</param>

        /// <param name="TableName">数据表名</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.Ace.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES; IMEX=1';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;
        }
    }
Epplus 简介:Epplus是一个使用Open Office XML(Xlsx)文件格式,能读写Excel 2007/2010文件的开源组件 功效:支持对excel文档的汇入汇出,图表(excel自带的图表基本都可以实现)的列印 使用:首先应该下载Epplus的dll文件 1> 添加dll文件至工程bin文件中 2>在程式中添加引用 using OfficeOpenXml; using OfficeOpenXml.Drawing; using OfficeOpenXml.Drawing.Chart; using OfficeOpenXml.Style; 3>所有的操作语句需要放置在下面的using中 using (ExcelPackage package = new ExcelPackage()) { } 4.添加新的sheet var worksheet = package.Workbook.Worksheets.Add(“sheet1"); 5.单元格赋值,这里多说一句,NPOI必须先创建单元格,然后再给单元格赋值,而Epplus不需要,直接找到单元格进行赋值就可以了. worksheet.Cells[int row, int col].Value = “”; 或者 worksheet.Cells["A1"].Value = “”; 6.合并单元格 worksheet.Cells[int fromRow, fromCol, int toRow,int toCol].Merge = true; 7.获取某一个区域 var rangeData= worksheet.Cells[fromRow, fromCol, toRow, toCol]; 8.设置字体 worksheet.Cells.Style.Font.Name= “正楷”; worksheet.Cells.Style.Font.Color worksheet.Cells.Style.Font.Size 9.设置边框的属性 worksheet.Cells.Style.Border.Left.Style= ExcelBorderStyle.Thin ; worksheet.Cells.Style.Border.Right.Style= ExcelBorderStyle.Thin; worksheet.Cells.Style.Border.Top.Style= ExcelBorderStyle.Thin; worksheet.Cells.Style.Border.Bottom.Style= ExcelBorderStyle.Thin; 10.对齐方式 worksheet.Cells.Style.HorizontalAlignment=ExcelHorizontalAlignment.Center; worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Bottom; 11. 设置整个sheet的背景色 worksheet.Cells.Style.Fill.PatternType= ExcelFillStyle.Solid; worksheet.Cells.Style.Fill.BackgroundColor.SetColor(Color.LightBlue); 12.折行显示 worksheet.Cells.Style.WrapText= true; 13.单元格自动适应大小 worksheet.Cells.Style.ShrinkToFit= true; 14.格式化单元格value值 worksheet.Cells.Style.Numberformat.Format= "0.00"; 15.锁定 worksheet.Cells["A1"].Style.Locked= true; 注:此处锁定某一个单元格的时候,只有在整个sheet被锁定的情况下才可以被锁定,不然加上锁定属性也是不起作用的~~ 二.Epplus另一个出色的地方就是支持图表的列印.功能的實現很簡單,難點在于需求比較細的點上,epplus可能不好實現,但是總的來說是比較好的一個列印圖表的工具 1.简单介绍一下可以实现的图表型: 直條圖、折綫圖、圓形圖、橫條圖、散佈圖、區域圖 等類型的圖表 2.使用:分为三步, 第一步是将需要显示在图表中的 数据列印到excel中. 第二步是创建所需要的图表型(折线图为例) var chart = (worksheet.Drawings.AddChart("LineChart", eChartType.Line) as ExcelLineChart); 第三步为图表添加第一步列印的数据区间就可以了 chart.Series.Add(Y軸顯示的數據源,X軸顯示的數據源) 3.图表的功能就这样实现了,很简单吧
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值