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登陆框。
代码如下:
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完成后,客户端会弹出保存窗口.