之前写的那个“asp.net控制Excel----弹出打开下载框”不知道为什么放在服务器上,在下载excel的那段代码上报了个错,显示拒绝访问。实在没看明白什么地方出的错。在网上又找了另外一段代码,实验过了很好使。
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = null;
Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
Microsoft.Office.Interop.Excel.Range oRng;
object missing = System.Reflection.Missing.Value;
//try
//{
String templatePath = Server.MapPath("../zhaosheng/xls/办暂人员.xls");
//创建一个Application对象并使其可见
app = new Microsoft.Office.Interop.Excel.ApplicationClass();
//打开模板文件,得到WorkBook对象
workbook = app.Workbooks.Open(templatePath, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing);
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
worksheet.Cells[5, 2] = "name";
//}
//catch (Exception ex)
//{
//}
excel.Application.Application.DisplayAlerts = false; //不显示提示信息
//显示效果
app.Visible = true;//这句话 自己试下就知道怎么回事了。可以注释了。
string tick = DateTime.Today.Year.ToString() + DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
workbook.SaveCopyAs(Server.MapPath(".") + "//xls//" + "办暂人员" + tick + ".xls");
workbook.Close(false, null, null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
workbook = null;
excel = null;
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
string ispath = Server.MapPath(".") + "//" + DateTime.Today.Year.ToString();
if (!System.IO.File.Exists(ispath))
{
Directory.CreateDirectory(ispath);
}
string path = Server.MapPath(".") + "//" + DateTime.Today.Year.ToString() + "//" + "办暂人员" + tick + ".xls";//Server.MapPath("办暂人员.xls");
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename = " + Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.WriteFile(file.FullName);
// 停止页面的执行
Response.End();