111,123
社区成员
发帖
与我相关
我的任务
分享
object oMissiong = System.Reflection.Missing.Value;
string ErrMsg = string.Empty;
string Title = "Excel中的标题";
//创建Excel对象
Microsoft.Office.Interop.Excel.ApplicationClass acExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook wb = acExcel.Workbooks.Add(true);
//不显示Excel
acExcel.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Sheets mysheet = null;
mysheet = wb.Sheets;
try
{
if (acExcel == null)
{
ErrMsg = "Error:请确定是否安装了Excel";
}
acExcel.Visible = false;
//先加入sheet
for (int i = 0; i < arr.Count; i++)
{
mysheet.Add(oMissiong, oMissiong, 1, oMissiong);
}
//删除多余的sheet,创建Excel时候会自动生成一个空白的sheet
for (int i = 0; i < wb.Sheets.Count; i++)
{
if (i == wb.Sheets.Count - 1)
{
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)mysheet.get_Item(i + 1);
ws.Delete();
}
}
for (int i = 0; i < arr.Count; i++)
{
//Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet;
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)mysheet.get_Item(i + 1);
ws.Name = "sheet的名称";
ws.PageSetup.CenterHorizontally = true; // 设置水平居中
Microsoft.Office.Interop.Excel.Range range = null;
}
//释放资源
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
ws = null;
}
// 保存文件到程序运行目录下
wb.SaveCopyAs(Server.MapPath("../ExcelFile/" + FileName + ".xls"));
wb.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
wb = null;
acExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(acExcel);
acExcel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
// 设置编码
string path = Server.MapPath("../ExcelFile/" + FileName + ".xls");
System.IO.FileInfo file = new System.IO.FileInfo(path);
Res.Clear();
Res.Charset = "GB2312";
Res.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
// 指定返回的是一个不能被客户端读取的流,必须被下载
Res.ContentType = "application/ms-excel";
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Res.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
//添加头信息,指定文件大小,让浏览器能够显示下载进度
Res.AddHeader("Content-Length", file.Length.ToString());
// 把文件流发送到客户端
Res.WriteFile(path);
// 停止页面的执行
Res.Flush();
Res.End();
Message = ErrMsg;
}
catch (Exception ex)
{
Message = ErrMsg;
}
finally
{
foreach (System.Diagnostics.Process pro in System.Diagnostics.Process.GetProcessesByName("Excel"))
pro.Kill();
}
System.GC.SuppressFinalize(this);