protected void ImportTo_Excel_Click(object sender, EventArgs e) { //DataTable dt = null; //Response.ContentType = "application/vnd.ms-excel"; //Response.AddHeader("Content-Disposition", "attachment;filename=" + // Server.UrlEncode(this.Page.Title) + "_" + System.DateTime.Now.ToString("yyMMdd_fff") + ".xls"); //Response.Charset = "GB2312"; //Response.ContentEncoding = Encoding.GetEncoding("GB2312"); //Response.Write(App_Code.Util.GetExcelString(dt)); //Response.End(); string connectionString = @"Data Source=192.168.0.20;Initial Catalog=Basedb;User ID=sa;Password=123456;Replication=True"; try { SqlConnection cn = new SqlConnection(connectionString); cn.Open(); try { string s = "select * from Inv_ItemSell "; SqlCommand cmd = new SqlCommand(s, cn); SqlDataReader dr = cmd.ExecuteReader(); Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { } xlApp.Application.Workbooks.Add(true); int row = 2, fieldcount; fieldcount = dr.FieldCount; for (int col = 0; col < fieldcount; col++) { xlApp.Cells[1, col + 1] = dr.GetName(col); } while (dr.Read()) { for (int col = 0; col < fieldcount; col++) { xlApp.Cells[row, col + 1] = dr.GetValue(col).ToString(); } row++; } xlApp.Visible = true; xlApp.Quit(); xlApp = null; //System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); string GUIDstringfile = System.Guid.NewGuid().ToString() + ".xls"; xlApp.Save(GUIDstringfile); System.IO.FileInfo file = new System.IO.FileInfo(GUIDstringfile); 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(); } catch (Exception ex) { } finally { cn.Close(); } } catch (Exception ex) { } finally { } }
IIS是不是没权限操作Microsoft.Office.Interop.Excel.Application,添加操作权限