现在的位置: 首页 > 综合 > 正文

生成EXECL表格 并生成本地文件

2012年10月20日 ⁄ 综合 ⁄ 共 2409字 ⁄ 字号 评论关闭

public void OutputExcel(DataView dv,string fileName)
    {
        GC.Collect();
        Excel.Application excel;// = new Application();
        int rowIndex = 1;
        int colIndex = 0;

        Excel._Workbook xBk;
        Excel._Worksheet xSt;

        excel = new Excel.ApplicationClass();

        xBk = excel.Workbooks.Add(true);

        xSt = (Excel._Worksheet)xBk.ActiveSheet;

        //
        //取得标题
        //
        foreach (DataColumn col in dv.Table.Columns)
        {
            colIndex++;
            excel.Cells[1, colIndex] = col.ColumnName;
            xSt.get_Range(excel.Cells[1, colIndex], excel.Cells[1, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
        }

        //
        //取得表格中的数据
        //
        foreach (DataRowView row in dv)
        {
            rowIndex++;
            colIndex = 0;
            foreach (DataColumn col in dv.Table.Columns)
            {
                colIndex++;
               

                        excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
            }
        }
 
        //
        //设置整个报表的标题的背景色 和字段宽度
        //
        xSt.get_Range(excel.Cells[1, 1], excel.Cells[1, colIndex]).Font.Bold = true;
        xSt.get_Range(excel.Cells[1, 1], excel.Cells[1, colIndex]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.ColorTranslator.FromHtml("#00CC66"));
        xSt.get_Range(excel.Cells[1, 1], excel.Cells[1, colIndex]).Columns.AutoFit();
        //
        //绘制边框
        //       //
        //显示效果
        //
        excel.Visible = false;
        xBk.SaveCopyAs(fileName);

        xBk.Close(false, null, null);

        excel.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
        xBk = null;
        excel = null;
        xSt = null;
        GC.Collect();

        System.IO.FileInfo file = new System.IO.FileInfo(fileName);
        Response.Clear();
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
        // 添加头信息,指定文件大小,让浏览器能够显示下载进度
        Response.AddHeader("Content-Length", file.Length.ToString());

        // 指定返回的是一个不能被客户端读取的流,必须被下载
        Response.ContentType = "application/ms-excel";

        // 把文件流发送到客户端
        Response.WriteFile(file.FullName);
        // 停止页面的执行
       
        Response.End();
       
    }

抱歉!评论已关闭.