个人项目实践,可行
asp.net c# 导出Excel
/// <summary>
/// al:要打印的记录集 columnname:表头显示名称
/// </summary>
public static void outtoExcel(ArrayList al,string[] columnname) {
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
Microsoft.Office.Interop.Excel._Worksheet wsheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
wsheet.Name = "报表";
int i = 1;
foreach (String[] str in al)
{
if (i == 1)//表头
{
//object[] columnname = daobean.getTableColumnName(tableFlag);
int k = 0;
//foreach (DictionaryContent str2 in columnname)
//{
foreach (string strname in columnname)
{
excel.Cells[1, k + 1] = strname;//表头初始化
k++;
}
//}
}
i++;
for (int j = 0; j < str.Length; j++)
{//进入内部循环,以增加表格列
excel.Cells[i, j+1] = str[j];
}
}
excel.Visible = true;
//Response.Write("<script>parent.delScreenConvert();</script>");
//======
string fileName = Global.getRamFileName();
workbook.SaveCopyAs(System.Web.HttpContext.Current.Server.MapPath(".") + "//excel//" + fileName + ".xls");
workbook.Close(false, null, null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wsheet);
workbook = null;
excel = null;
wsheet = null;
string path = System.Web.HttpContext.Current.Server.MapPath("excel//" + fileName + ".xls");
System.IO.FileInfo file = new System.IO.FileInfo(path);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Charset = "UTF-8";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpContext.Current.Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
System.Web.HttpContext.Current.Response.WriteFile(file.FullName);
// 停止页面的执行
System.Web.HttpContext.Current.Response.End();
//CheckBoxList1.Items.Clear();
}