NPOI的基本使用参照:https://www.cnblogs.com/lixiaobin/p/NPOI.html
既存文档读取修改方法
既存Excel文档修改保存注意使用FileMode.Create,不然文档将会被损害无法打开。
IWorkbook book = null; using (var file = File.Open(path, FileMode.OpenOrCreate, FileAccess.Read)) { book = WorkbookFactory.Create(file); file.Close(); } ISheet outputSheet = book?.GetSheet(sheetName) ?? book?.CreateSheet(sheetName); // 修改数据 // 省略 using (var file = new FileStream(path, FileMode.Create, FileAccess.Write)) { book.Write(file); file.Close(); }
单元格复制方法
如果你想将一个Excel文档的值复制到另一个Excel文档,格式设置需要注意使用CloneStyleFrom方法。
var sheet = book.CreateSheet("test"); var row = sheet.CreateRow(1); var newCell=row.CreateCell(1); newCell.SetCellValue(oldCell.StringCellValue); var newCellStyle = book.CreateCellStyle(); newCellStyle.CloneStyleFrom(oldCell.CellStyle); newCell.CellStyle = newCellStyle;