var app= new Application{Visible=false}; Workbook workbook = app.Workbooks.Add(); Worksheet worksheet = app.ActiveSheet; worksheet.Cells[1, 1].value = "名称"; worksheet.Cells[1, 2].value = "价格"; worksheet.Cells[1, 3].value = "供应商"; int row = 2; foreach (var item in geta) { worksheet.Cells[row, 1].value = item.ProductName; worksheet.Cells[row, 2].value = item.ProductPrice; worksheet.Cells[row, 3].value = item.SupllyName; row++; } string savePath = Server.MapPath("~/upload/");//指定上传文件在服务器上的保存路径 //检查服务器上是否存在这个物理路径,如果不存在则创建 if (!System.IO.Directory.Exists(savePath)) { System.IO.Directory.CreateDirectory(savePath); } string filen = DateTime.Now.ToString("yyyyMMddHHmmss") + "demo.xls"; string filea = savePath + filen; //这里是绝对地址 string fil = "~/upload/" + filen; //这里是相对地址 workbook.SaveAs(Filename: filea, FileFormat: XlFileFormat.xlWorkbookNormal); app.ActiveWorkbook.Close(); app.Application.Quit(); DownLoad(fil); } //这个是下载到桌面的方法,没实现自选路径 //注意,要相对地址 public static void DownLoad(string FileName) { FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(FileName)); //以字符流的形式下载文件 FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(FileName), FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); HttpContext.Current.Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileInfo.Name, System.Text.Encoding.UTF8)); HttpContext.Current.Response.BinaryWrite(bytes); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); }
时间: 2024-10-08 17:00:10