nissl-lab / npoi

a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.
Apache License 2.0
5.73k stars 1.43k forks source link

XSSFWorkbook write issue #1395

Closed KoakiMiku closed 1 month ago

KoakiMiku commented 3 months ago

NPOI Version

2.7.1

File Type

Issue Description

I have a template excel file, when I use the following code and write to a new excel file, both "1.xlsx" and "2.xlsx" are modified. Is this behavior correct?

var templateFile = "./1.xlsx";
var newFile = "./2.xlsx";

using var workbook = new XSSFWorkbook(templateFile);
var sheet = workbook.GetSheetAt(0);
var baseCell = sheet.GetRow(1).GetCell(0);
var cell = sheet.CreateRow(2).CreateCell(0);
cell.SetCellValue("Test");
cell.CellStyle = baseCell.CellStyle;

using var fileStream = new FileStream(newFile, FileMode.OpenOrCreate);
workbook.Write(fileStream, false);

Now I am using the following code to avoid this issue.

var templateFile = "./1.xlsx";
var newFile = "./2.xlsx";

File.Copy(templateFile, newFile, true);
using var workbook = new XSSFWorkbook(newFile);
var sheet = workbook.GetSheetAt(0);
var baseCell = sheet.GetRow(1).GetCell(0);
var cell = sheet.CreateRow(2).CreateCell(0);
cell.SetCellValue("Test");
cell.CellStyle = baseCell.CellStyle;

workbook.Write(Stream.Null, false);
tonyqus commented 1 month ago

I don't think 1.xlsx will be modified if you don't call workbook.Write with old filestream. There is no automatic saving logic for workbook.