1、前言
最近有朋友反馈使用NPOI
向已有的xlsx
文件中添加数据后,要么无法保存新增数据,要么直接报出下图所示的错误,下面就来说一下如何利用NPOI
向一个已有的xlsx
文件添加数据的方法。
2、实现方法
新建一个xlsx
文件,其数据如下图所示:
如果要向该文件添加一行新的数据,只要分三步走即可:
1、创建文件流读取xlsx
2、添加新的数据
3、创建文件流写入xlsx
using System;
using System.IO;
namespace NPOIApp
{
class Program
{
static void Main(string[] args)
{
// 第一步:读取文件流
NPOI.SS.UserModel.IWorkbook workbook;
using (FileStream stream = new FileStream(@"C:\Users\dongshenfeng\Desktop\test.xlsx", FileMode.Open, FileAccess.Read))
{
workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(stream);
}
// 第二步:创建新数据行
NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
NPOI.SS.UserModel.IRow row = sheet.CreateRow(sheet.LastRowNum + 1);
NPOI.SS.UserModel.ICell cell;
// 创建单元格样式
NPOI.SS.UserModel.ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
// 添加测试数据
cell = row.CreateCell(0);
cell.CellStyle = cellStyle;
cell.SetCellValue("3");
cell = row.CreateCell(1);
cell.CellStyle = cellStyle;
cell.SetCellValue("王五");
cell = row.CreateCell(2);
cell.CellStyle = cellStyle;
cell.SetCellValue("男");
cell = row.CreateCell(3);
cell.CellStyle = cellStyle;
cell.SetCellValue("27");
// 第三步:写入文件流
using (FileStream stream = new FileStream(@"C:\Users\dongshenfeng\Desktop\test.xlsx", FileMode.Create, FileAccess.Write))
{
workbook.Write(stream);
workbook.Close();
}
Console.ReadKey(true);
}
}
}
运行结果如下如所示: