我创建了一个excel文件,并在(0,0)[row,cell]中插入一个新值为 Hello . 第二次我打开相同的excel文件,相同的工作表并使用另一个字符串值更新相同的(0,0)单元格 .
代码运行成功,没有任何错误,但文件已损坏,无法打开 .
CODE
namespace PractiseProject
{
public static class ExcelNPOI
{
static IWorkbook workbook;
static ISheet sheet;
static IRow row;
static ICell cell;
static string file = "C:/Users/MSTEMP/Documents/Files/Test.xlsx";
static string sheetName = "Testcase";
public static void createExcel()
{
string firstValue = "Hello";
if (!File.Exists(file))
{
using (FileStream str = new FileStream(file, FileMode.Create, FileAccess.Write))
{
workbook = new XSSFWorkbook();
sheet = workbook.CreateSheet(sheetName);
row = sheet.CreateRow(0);
cell = row.CreateCell(0);
cell.SetCellValue(firstValue);
workbook.Write(str);
str.Close();
}
}
else
{
using (FileStream rstr = new FileStream(file, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(rstr);
sheet = workbook.GetSheet(sheetName);
using (FileStream wstr = new FileStream(file, FileMode.Open, FileAccess.ReadWrite))
{
string secondValue = "changes";
row = sheet.GetRow(0);
cell = row.GetCell(0);
cell.SetCellValue(secondValue);
Debug.Print(cell.ToString());
workbook.Write(wstr);
wstr.Close();
}
rstr.Close();
}
}
}
}
}
在调试模式下,设置第二个值后 cell.SetCellValue(secondValue); 我可以通过 Debug.Print(cell.ToString()); 查看该值,并在控制台中打印该值 . 但是当写入工作簿时,文件会被破坏 . 引导我伸出援手 .