简单实现C#生成Excel 2007文件并下载
添加引用Microsoft Excel 12.0 Object Library,我这里使用的是Office 2007。
有必要的话,需要修改web.config:
<identity impersonate="true" userName="administrator" password="password"/>代码如下:
Application app = null;
Workbook wb = null;
Worksheet sheet = null;
try
{
app = new Application();
app.Visible = false;
wb = (Workbook)app.Workbooks.Add(Missing.Value);
sheet = (Worksheet)wb.ActiveSheet;
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", Path.GetTempPath(), 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];另外是finally中的代码,目的关闭Excel.exe进程。
在一个button事件或者其他postback事件中,使用上面的代码生成文件后,附加下面代码,就可以实现下载:
Response.AppendHeader("Content-Disposition", "attachment;filename=MassPay.xlsx");
Response.ContentType = "application/ms-excel";
Response.WriteFile(fileName);

浙公网安备 33010602011771号