简体   繁体   English

NPOI 2.2.1生成不正确的XLSX文件

[英]NPOI 2.2.1 generates incorrect XLSX file

I have NPOI 2.2.1 and I realized that when generating XLSX file and opening with Excel 2013, a message box telling that a problem was encountered but Excel could try to recover from it. 我有NPOI 2.2.1,我意识到在生成XLSX文件并使用Excel 2013打开时,会出现一个消息框,指出遇到了问题,但Excel可以尝试从中恢复。 When I click "Yes", the sheet is finally shown. 当我单击“是”时,最终显示该工作表。

This is the code: 这是代码:

        IWorkbook workbook = new XSSFWorkbook();
        ISheet sheet = workbook.CreateSheet(this.Title);

        using (var exportData = new MemoryStream())
        {
            workbook.Write(exportData);
            return exportData.GetBuffer();
        }

As you see, I am only creating the workbook, adding a sheet and then returning the bytes array. 如您所见,我仅创建工作簿,添加工作表,然后返回bytes数组。 That array is stored in file using this code: 使用以下代码将该数组存储在文件中:

            string targetFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), String.Concat(btnExportar.Tag, "_", DateTime.Now.ToString("yyyyMMddHHmmss"), ".xlsx"));
            System.IO.File.WriteAllBytes(targetFile, xls.GetExcelData());

With XLS files there is no problem. 使用XLS文件没有问题。

Regards Jaime 问候海梅

The problem is not with NPOI, but with your use of GetBuffer() . 问题不在于NPOI,而在于您对GetBuffer()的使用 That is not the method you want to use for this purpose, as GetBuffer() returns the raw buffer underlying the memory stream (usually oversized), without cutting it off at the current position of the stream . 这不是您要用于此目的的方法,因为GetBuffer()返回位于内存流下面的原始缓冲区(通常是超大的), 而不会在流的当前位置切断它 This will leave uninitialized data at the end, causing the error message in Excel. 这将在末尾留下未初始化的数据,从而在Excel中导致错误消息。

The get all the bytes from a MemoryStream, use ToArray() : 要从MemoryStream获取所有字节,请使用ToArray()

using (var exportData = new MemoryStream())
{
    workbook.Write(exportData);
    // return exportData.GetBuffer();
    return exportData.ToArray();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM