[英]Npoi xls file save corrupts excel file
因此,我能夠打開和瀏覽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);
}
您是否有多行單元格內容(帶有換行符)?
我只是在第0行的列標題遇到了這樣的問題_x000a_
通過將換行符替換為_x000a_
(即line1_x000a_line2
)來編碼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_"));
}
嘗試類似
FileStream sw = File.Create(excelLocation);
wbXLS.Write(sw);
sw.Close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.