C# Aspx Web 导出Excel2007-xlsx格式文件用NPOI插件的问题

1,730 阅读2分钟

文档文件用NPOI插件, 在有导出.xlsx文件时,在打开时总报:

错误提示: Excel在“春天Excel2007.xlsx”中发现不可读取内容。是否恢复工作簿的内容?如果信任此工作簿的来源,请单击“是”。 单击“是”后:Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃.

处理Excel2007、2010文件,格式.xlsx文件存在一个问题,在调用 Write方法之后关闭了传入的文件流

//文件流传入内存
var ms = MemoryStream();
//ms.Length;//会抛出不可读异常
var fileSize = file.ToArray().Length;//改用

问题如何处理呢?直接上代码如下:

由于 使用MemoryStream 这个有问题,先改用 FileStream

public void CreateExcelV2(List<work_order> list, Dictionary<string, string> cols, string FileType, string FileName)
        {
            string path = MapPath("~/Files");
            if (Directory.Exists(path) == false) Directory.CreateDirectory(path);
            string savePath = path + "/" + FileName + ".xlsx";

            try
            {
                var workbook = new XSSFWorkbook();//2007版本 xlsx
                //var workbook = new HSSFWorkbook();
                #region 创建生成表格文件.xlsx
                var sheet = workbook.CreateSheet("Sheet1");
                //key 键 自定义宽度
                var regNum = new Regex(@"\d+");
                //写入列名
                var row = sheet.CreateRow(0);
                int i = 0;
                foreach (var col in cols.Values)
                {
                    row.CreateCell(i++).SetCellValue(col);
                }
                //写入数据
                i = 0;
                foreach (var item in list)
                {
                    row = sheet.CreateRow(i + 1);
                    int j = 0;
                    foreach (var key in cols.Keys)
                    {
                        row.CreateCell(j++).SetCellValue(getModelKeyValue(key, item));
                    }
                    i++;
                }
                #endregion
                #region 写出表格文件,下载
                Response.Clear();
                Response.Charset = "UTF-8";
                Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                Response.Buffer = true;
                Response.ContentType = FileType;
                //调用这个后会关于文件流,在HSSFWorkbook不会关闭所以在处理时应注意 
                using (var fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(fs);
                    fs.Close();
                }
                using (var fs = new FileStream(savePath, FileMode.Open, FileAccess.Read))
                {
                    long fileSize = fs.Length;
                    byte[] fileBuffer = new byte[fileSize];
                    fs.Read(fileBuffer, 0, (int)fileSize);
                    
                    Response.AddHeader("Content-Length", fileSize.ToString());
                    Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}.xlsx\"", HttpUtility.UrlEncode(FileName, Encoding.UTF8)));

                    Response.BinaryWrite(fileBuffer);

                    Context.ApplicationInstance.CompleteRequest();
                    Response.Output.Flush();

                    fs.Close();
                }
                /*
                using (var file = new MemoryStream())
                {
                    workbook.Write(file);

                    //加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
                    Response.AddHeader("Content-Length", (file.ToArray().Length).ToString());
                    Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}.xlsx\"", HttpUtility.UrlEncode(FileName, Encoding.UTF8)));
                    Response.BinaryWrite(file.GetBuffer());
                    Context.ApplicationInstance.CompleteRequest();
                    Response.Output.Flush();
                    //Response.Flush();

                    file.Flush();
                    file.Close();
                }
                */
                #endregion
            }
            catch (Exception ex)
            {
                Response.Write("400, file download excetion. "+ex.Message);
            }
            finally
            {
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }
                Response.End();//不可以放在try 内,会抛出异常
            }
        }


参考来源:

https://www.cnblogs.com/kaiwanlin/p/5782834.html