.NET EP Plus导出Excel,解决火狐或ie乱码的问题
.NET EP Plus导出Excel,解决火狐或ie乱码的问题 通过流导出在浏览器端,保存在本地。
1 using (ExcelPackage package = new ExcelPackage()) 2 { 3 ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1"); 4 //worksheet.Cells[1, 1, 1, 3].Merge = true; 5 //worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中 6 //worksheet.Cells[1, 1].Style.Font.Bold = true;//字体为粗体 7 //worksheet.Cells[1, 1].Style.Font.Size = 12;//字体大小 8 worksheet.Cells[1, 1].Value = "联系方式"; 9 worksheet.Cells[2, 1].Value = "17777777777"; 10 worksheet.Cells[3, 1].Value = "15977777777"; 11 worksheet.Cells[4, 1].Value = "13677777777"; 12 worksheet.Cells[1, 2].Value = "被催收人"; 13 worksheet.Cells[2, 2].Value = "周女士"; 14 worksheet.Cells[3, 2].Value = "张三"; 15 worksheet.Cells[4, 2].Value = "李四"; 16 17 18 byte[] bytes = package.GetAsByteArray(); 19 // 清除缓存区流中的所有内容输出 20 context.Response.Clear(); 21 // 设置缓冲输出为true,后台编辑的文件写到内存流中了 22 context.Response.Buffer = true; 23 // 设置编码格式 ContentEncoding是管字节流到文本的,而Charset是管在浏览器中显示的 24 //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 25 //Response.Charset = "UTF-8"; 26 27 string userAgent = context.Request.ServerVariables["http_user_agent"].ToLower(); 28 29 //如果不是火狐浏览器 30 if (userAgent.IndexOf("firefox") == -1) 31 { 32 // 将HTTP头添加到输出流,指定默认名 33 context.Response.AddHeader("Content-Disposition", string.Format(@"attachment;filename=""{0}""", HttpUtility.UrlEncode("发送短信模板" + "." + "xlsx", Encoding.UTF8), Encoding.UTF8)); 34 //Response.ContentEncoding = System.Text.Encoding.UTF8; 35 } 36 else 37 { 38 // 将HTTP头添加到输出流,指定默认名 39 context.Response.AddHeader("Content-Disposition", string.Format(@"attachment;filename=""{0}""", "发送短信模板" + "." + "xlsx")); 40 } 41 42 // 设置输出流的HTTP MIME类型为application/vnd.ms-excel 43 context.Response.ContentType = "application/vnd.ms-excel"; 44 context.Response.AddHeader("Content-Length", bytes.Length.ToString()); 45 // 将指定的文件写入HTTP内容输出流 46 context.Response.OutputStream.Write(bytes, 0, bytes.Length); 47 //防止文件名含中文出现乱码而进行编码 48 // Response.BinaryWrite(bytes); 49 // 向客户端发送当前所有缓冲的输出 50 context.Response.Flush(); 51 // 将当前所有缓冲的输出关闭 52 context.Response.Close(); 53 }