asp.net数据导出到excel表格,并设置表格样式

1.首先在项目中添加引用

2.添加该COM组件后会再文件夹中出现一个Interop.Excel.dll的文件,将之前的Microsoft Excel 11.0 Object Library组件删除,添加新的Interop.Excel.dll的引用。

然后添加excel的.net组件

3.现在开始贴代码:

导出excel文件的样式设计、保存、释放资源都存放在一个Share.cs的类文件中

using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

#region 设置excel样式并保存到PC
        /// <summary>
        /// 设置excel表格格式
        /// </summary>
        /// <param name="ksCell">开始列索引</param>
        /// <param name="jsCell">结束列索引</param>
        /// <param name="ksRow">开始行索引</param>
        /// <param name="jsRow">结束行索引</param>
        /// <param name="xls">Excel.Application对象</param>
        /// <param name="filepath">文件保存完整路径</param>
        public static Excel.Application TableCss(int ksCell, int jsCell, int ksRow, int jsRow, Excel.Application xls)
        {
            //设置报表表格为最适应宽度
            //
            xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Select();
            xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Columns.AutoFit();
            //xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Columns.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            
            //
            //设置整个报表的标题为跨列居中
            //
            xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Select();
            xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].HorizontalAlignment = XlHAlign.xlHAlignCenter;
            //
            //绘制边框
            //xSt.Range[xls.Cells[rowIndex, 1], xls.Cells[1, rowIndex]].Borders.LineStyle = 1;
            xls.Range[xls.Cells[jsRow, ksCell], xls.Cells[ksRow, ksCell]].Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗
            xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[ksRow, jsCell]].Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
            xls.Range[xls.Cells[ksRow, jsCell], xls.Cells[jsRow, jsCell]].Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
            xls.Range[xls.Cells[jsRow, ksCell], xls.Cells[jsRow, jsCell]].Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗

            xls.Visible = false;
            return xls;
        }
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int/// <summary>
        /// 保存excel文件并结束当前EXCEL进程
        /// </summary>
        /// <param name="xls"></param>
        /// <param name="filepath"></param>
        public static void SaveExcel(Excel.Application xls, string filepath)
        {
            xls.ActiveWorkbook.SaveAs(filepath, Excel.XlFileFormat.xlExcel7, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
            xls.Workbooks.Close();
            xls.Quit();
            IntPtr t = new IntPtr(xls.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
            int k = 0;
            GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
            p.Kill(); //关闭进程k 
            GC.Collect();
        }

#endregion

4.页面导出代码:

        #region 导出excel文件      /// <summary>
        /// 导出数据
        /// </summary>
        protected void btnPagedata_Click(object sender, EventArgs e)
        {
            try
            {
                string ddidlist = " 0,1,2,3,4 ";
                System.Data.DataTable ds = new BLL().GetList(" id in (" + ddidlist + ")").Tables[0];
                DoExport(ds, @"D:\" + DateTime.Now.ToString("yy-MM-dd") + "Excel.xls");
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert('数据导出成功!');</script>");
            }
            catch
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>alert('数据导出失败!');</script>");
            }
        }
        /// <summary>
        /// 导出excel文件
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="FilePath"></param>
        private void DoExport(DataTable ds, string FilePath)
        {
            Excel.Application xls = new Excel.Application();
            int rowIndex = 1;
            //int ceelindex = 4;
            xls.Application.Workbooks.Add(true);
            if (ds.Rows.Count > 0)
            {
                xls.Cells[1] = "ID";
                xls.Cells[2] = "价格";
                xls.Cells[3] = "产品";
                xls.Cells[4] = "简称";
                xls.Cells[5] = "时间";
                xls.Cells.NumberFormat = "@";//防止存在超过11位的全数字的列在导入后会被用科学计数法显示
                foreach (DataRow row in ds.Rows)
                {
                    rowIndex++;
                    xls.Cells[rowIndex, 1] = row["id"].ToString();
                    xls.Cells[rowIndex, 2] = row["ji"].ToString() + "RMB";
                    xls.Cells[rowIndex, 3] = row["cm"].ToString();
                    xls.Cells[rowIndex, 4] = row["ss"].ToString();
                    xls.Cells[rowIndex, 5] = row["time"].ToString();
                }
                Share.TableCss(1, 5, 1, rowIndex, xls);//设置excel边框格式
                Share.SaveExcel(xls, FilePath);//保存excel文件,并且结束当前excel的进程
            }
        }
#endregion

 

使用该方法导出Excel文件必须要求服务器上安装有最低office 2003的组件才能正常运行,不过也存在不需要引用的方式的方式输出,比如直接编辑成html格式,还有种一个国外牛人写的dll,可以达到与上面相同的效果导出excel不需要安装office工具。

解决方案:首先下载MyXls.dll下载地址:http://sourceforge.net/projects/myxls/files/  。然后引用 dll。

不过这种方法自己还没有使用过,所以暂时不能为大家贴出代码。

如果大家对我代码有什么不同的意见还希望能在下面留言

 

 

posted @ 2013-12-21 09:43  .Justme  阅读(3974)  评论(0编辑  收藏  举报