【发布时间】:2019-09-17 12:36:40
【问题描述】:
我制作了一个程序,用于将一个单元格分成两个单元格并将它们写入不同的工作表,但是在我运行它之后,excel 文件被损坏了。
IWorkbook workbook;
using(FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(stream);
}
IWorkbook newWorkbook = new XSSFWorkbook();
ISheet sheet = workbook.GetSheetAt(0);
ISheet oneWordSheet = newWorkbook.CreateSheet();
ISheet moreWordsSheet = newWorkbook.CreateSheet();
IRow tmpRow;
for(int i = 5; i < 100/*sheet.LastRowNum*/ + 1; i++)
{
tmpRow = sheet.GetRow(i);
string[] strings = tmpRow.GetCell(2).StringCellValue.Split(' ');
string companyName = strings[0];
bool parseFailed = true;
for(int j = 1; parseFailed && j < strings.Length; j++)
{
try
{
int.Parse(strings[j]);
parseFailed = false;
}
catch (FormatException)
{
companyName += strings[j];
j++;
}
}
tmpRow.CreateCell(4).SetCellValue(companyName);
if(companyName.Trim().Split(' ').Length < 2)
{
copyRowToSheet(tmpRow, oneWordSheet);
}
else
{
copyRowToSheet(tmpRow, moreWordsSheet);
}
}
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Write))
{
newWorkbook.Write(stream);
}
我做了一个这样的 copyRowToSheet 方法。应该是正确的
private static void copyRowToSheet(IRow row, ISheet sheet)
{
IRow newRow = sheet.CreateRow(sheet.LastRowNum + 1);
newRow.CreateCell(0).SetCellValue(row.GetCell(0).NumericCellValue);
newRow.CreateCell(1).SetCellValue(row.GetCell(1).StringCellValue);
newRow.CreateCell(2).SetCellValue(row.GetCell(4).StringCellValue);
newRow.CreateCell(3).SetCellValue(row.GetCell(2).StringCellValue);
newRow.CreateCell(4).SetCellValue(row.GetCell(3).StringCellValue);
}
我尝试从工作簿而不是 newWorkbook 写入,但它仍然损坏文件,我还尝试删除 copyRowToSheet 方法(只是将 if 和 else case 都留空,但结果不会改变......
编辑: 我尝试删除整个程序,只留下以下内容:
IWorkbook workbook;
using(FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(stream);
stream.Close();
}
IWorkbook newWorkbook = new XSSFWorkbook();
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Write))
{
workbook.Write(stream);
stream.Close();
}
如果我没记错的话,这应该只读取文件然后将其保存回来而不进行任何编辑,但它仍然会损坏文件
【问题讨论】:
-
嗨@miclemattiol 我的回答有帮助吗?如果您可以将其标记为已接受的答案,那就太好了:-)
标签: c# excel corruption npoi