asp.net 下载和在线预览Excel的方法

时间:2024-04-17 16:49:29

直接代码,红色字体是对大家有用地。

public string ExcelCache
        {
            get
            {
                string _path = Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "ExcelBuffer\\");
                if (!Directory.Exists(_path))
                {
                    Directory.CreateDirectory(_path);
                }
                return _path;
            }

        }

                Report rpt = Report.LoadReport(Convert.ToInt32(reportID));
                ExcelHeaderBuilder builder = new ExcelHeaderBuilder();
                ExcelWorkbook book = new ExcelWorkbook();
                book.CreateSheet(sheetName);
                book.SetActiveSheet = sheetName;
                ExcelWorksheet sheet = book.GetSheet(sheetName);
                ExcelCellStyle style = book.CreateStyle();
                style.BorderColour = EnumColours.Black;
                style.BorderLineStyle = EnumLineStyle.Thin;
                style.Font.Name = "黑体";
                style.Font.Size = 12;
                style.HorizontalAlignment = EnumHorizontalAlignment.Center;
                style.VerticalAlignment = EnumVerticalAlignment.Center;

                builder.Style = style;
                builder.MakeHeader(sheet, rpt);

                book.Save(path);
                    //下载
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(path));
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    HttpContext.Current.Response.Charset = "GB2312";
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                    HttpContext.Current.Response.WriteFile(path);
                    HttpContext.Current.Response.Flush();
            
                    //在线
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + Path.GetFileName(path));
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    HttpContext.Current.Response.Charset = "GB2312";
                    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                    HttpContext.Current.Response.WriteFile(path);
                    HttpContext.Current.Response.Flush();