c# 导出excel 通过模板

private void Bind()
    {
        //模板文件
        string TempletFileName = Server.MapPath("template.xls");
        //导出文件
        string ReportFileName = Server.MapPath("out.xls");

        string strTempletFile = Path.GetFileName(TempletFileName);
        //将模板文件复制到输出文件 
        FileInfo mode = new FileInfo(TempletFileName);
        mode.CopyTo(ReportFileName, true);

        //打开excel
        object missing = Missing.Value;
        Application app = null;
        Workbook wb = null;
        Worksheet ws = null;
        Range r = null;
        //
        app = new Microsoft.Office.Interop.Excel.Application();
        wb = app.Workbooks.Open(ReportFileName, false, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
        app.Visible = true;

        //得到WorkSheet对象
        ws = (Worksheet)wb.Worksheets.get_Item(1);

        //添加或修改WorkSheet里的数据
        ws.Cells[1, 1] = "100";
        ws.Cells[2, 1] = "100";
        ws.Cells[2, 2] = "100";
        //代码里写个公式
        r = (Range)ws.Cells[2, 3];
        r.Formula = "=A2*B2";

        //输出Excel文件并退出
        wb.Save();
        wb.Close(null, null, null);
        app.Workbooks.Close();
        app.Application.Quit();
        app.Quit();

        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

        ws = null;
        wb = null;
        app = null;

        string path = Server.MapPath("out.xls");

        System.IO.FileInfo file = new System.IO.FileInfo(path);
        Response.Clear();
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        // 添加头信息,为"文件下载/另存为"对话框指定默认文件名 
        Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("利益冲突问题投诉受理登记表.xls"));
        // 添加头信息,指定文件大小,让浏览器能够显示下载进度 
        Response.AddHeader("Content-Length", file.Length.ToString());

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

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

        Response.End(); 
    }
添加COM引用,包括:Microsoft.Excel.x.0.Object.Library,Microsoft.Office.x.0.Object.Library 

建议安装正版OFFICE,而且版本在11.0以上(Office2003以上),引用以上两个Com后,在项目引用栏发现多了Excel、Microsoft.Office.Core,VBIDE三个 Library.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值