码迷,mamicode.com
首页 > 其他好文 > 详细

导出excel,可以另存为源代码

时间:2015-09-25 20:02:31      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

           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();
        }

  

导出excel,可以另存为源代码

标签:

原文地址:http://www.cnblogs.com/500k/p/4839068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!