C#生成Excel 2007文件并下载

添加引用Microsoft Excel 12.0 Object Library,我这里使用的是Office 2007。

有必要的话,需要修改web.config:
<identity impersonate="true" userName="administrator" password="password"/>
目的是使用这个账号来运行Excel程序,曾经使用Word 2007在代码中生成XPS文件,因为没有如此修改web.config,初始化Word程序时,得到无权限的异常或者弹出Windows登陆框。

代码如下:

public void exceport()
        {
            Application app = null;
            Workbook wb = null;
            Worksheet sheet = null;

            try
            {
                //保存到web临时目录
                //string path = @"D:\" + DateTime.Now.ToString(@"yyyy-MM-dd-HHmmss") + ".xlsx";
                app = new Application();
                app.Visible = false;

                wb = (Workbook)app.Workbooks.Add(Missing.Value);
                sheet = (Worksheet)wb.ActiveSheet;

                List<String[]> contents = new List<string[]>();
                string[] A = { "123", "hwt", "xyz"};
                contents.Add(A);
                string[] B = { "456", "tyu", "abc"};
                contents.Add(B);

                for (int i = 0; i < contents.Count; i++)
                {
                    String[] item = contents[i];

                    for (int j = 0; j < item.Length; j++)
                        sheet.Cells[i + 1, j + 1] = item[j];
                }
                wb.Saved = true;

                string fileName = String.Format("{0}{1}.xlsx", System.AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.Ticks);
                app.ActiveWorkbook.SaveCopyAs(fileName);

                //return fileName;
            }
            finally
            {
                wb.Close(null, null, null);
                app.Workbooks.Close();
                app.Quit();
                Marshal.ReleaseComObject((object)app);
                Marshal.ReleaseComObject((object)wb);
                Marshal.ReleaseComObject((object)sheet);
                GC.Collect();
            }

            
        }

需要注意的是:

sheet.Cells[i+1, j+1] = item[j];
cell要从一行一列开始填值,不能从零行零列。
另外是finally中的代码,目的关闭Excel.exe进程。

在一个button事件或者其他postback事件中,使用上面的代码生成文件后,附加下面代码,就可以实现下载:
                    Response.AppendHeader( " Content-Disposition " " attachment;filename=MassPay.xlsx " ); 
                    Response.ContentType 
=   " application/ms-excel " ;
                    Response.WriteFile(fileName);
postback完成后,客户端会弹出保存窗口.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值