【问题标题】:Npoi xls file save corrupts excel fileNpoi xls 文件保存损坏 excel 文件
【发布时间】:2017-04-27 14:43:57
【问题描述】:

所以我能够打开并挖掘一个 xls (Excel 97-2003) 文件。但是,问题是当我尝试保存它时。在我保存它并成功后,我去手动打开 Excel 文件并得到一个错误,说它无法打开 Excel 文件并且它已损坏。无论我是否进行任何更改,都会发生这种情况。

我仍然能够在程序中打开 excel 文件并读取数据。

我正在使用 NPOI 2.2.1 和 2.3.0(我通过 Nuget 安装)。两个版本的结果相同。

string excelLocation = settings.GetExcelDirectory() + week.ExcelLocation;
HSSFWorkbook wbXLS;

// Try to open and read existing workbook
using (FileStream stream = new FileStream(excelLocation, FileMode.Open, FileAccess.Read))
{
    wbXLS = new HSSFWorkbook(stream);
}

ISheet sheet = wbXLS.GetSheet("Schedule");
using (FileStream stream = new FileStream(excelLocation, FileMode.Create, FileAccess.Write))
{
    wbXLS.Write(stream);
}

【问题讨论】:

  • 您的代码在我看来是正确的,而且对我来说效果很好(当我打开文件时 Excel 不会抱怨)。

标签: c# excel xls excel-2003 npoi


【解决方案1】:

您是否有多行单元格内容(带有换行符)?
我刚刚在第 0 行的列标题中遇到了这样的问题。 Excel 通过将换行符替换为_x000a_(即line1_x000a_line2)来编码换行符,NPOI 不会这样做。
尝试使用 nuget 2.3.0 和 xlsx 文件,但也可能对您的情况有所帮助。

我在保存之前通过替换换行来解决(并验证了原因):

// Encode LineFeeds in column headers (row 0)
IRow rowColHeaders = sheet.GetRow(0);
foreach (ICell cell in rowColHeaders.Cells)
{
    string content = cell.StringCellValue;
    if (content.Contains("\n"))
        cell.SetCellValue(content.Replace("\n", "_x000a_"));
}

【讨论】:

    【解决方案2】:

    试试类似的东西

         FileStream sw = File.Create(excelLocation);
    
         wbXLS.Write(sw);
    
         sw.Close();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多