因为自己所用到的NPOI库是网上找到的,版本和自己的VS环境之间不一定适配,因此出现了这种错误。
直接去VS工具入口下载与VS版本适配的NPOI库即可
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using NPOI.XSSF.UserModel; using System.IO; using NPOI.POIFS.FileSystem;
static void Main(string[] args) { HSSFWorkbook workbook2003 = new HSSFWorkbook(); //新建工作簿 workbook2003.CreateSheet("Sheet1"); //新建1个Sheet工作表 HSSFSheet SheetOne = (HSSFSheet)workbook2003.GetSheet("Sheet1"); //获取名称为Sheet1的工作表 //对工作表先添加行,下标从0开始 for (int i = 0; i < 2; i++) { SheetOne.CreateRow(i); //创建10行 } //对每一行创建10个单元格 HSSFRow SheetRow = (HSSFRow)SheetOne.GetRow(0); //获取Sheet1工作表的首行 HSSFRow SheetRow1 = (HSSFRow)SheetOne.GetRow(1); //获取Sheet1工作表的1行 HSSFCell[] SheetCell = new HSSFCell[10]; HSSFCell[] SheetCell1 = new HSSFCell[10]; for (int i = 0; i < 10; i++) { SheetCell[i] = (HSSFCell)SheetRow.CreateCell(i); //为第一行创建10个单元格 } for (int i = 0; i < 10; i++) { SheetCell1[i] = (HSSFCell)SheetRow1.CreateCell(i); //为第一行创建10个单元格 } //创建之后就可以赋值了 SheetCell[0].SetCellValue(true); //赋值为bool型 SheetCell[1].SetCellValue(0.000001); //赋值为浮点型 SheetCell[2].SetCellValue("Excel2003"); //赋值为字符串 SheetCell[3].SetCellValue("123456789987654321");//赋值为长字符串 for (int i = 4; i < 10; i++) { SheetCell[i].SetCellValue(i); //循环赋值为整形 } for (int i = 0; i < 10; i++) { SheetCell1[i].SetCellValue(i); //循环赋值为整形 } FileStream file2003 = new FileStream(@"D:\Excel2003.xls", FileMode.Create); workbook2003.Write(file2003); file2003.Close(); workbook2003.Close(); FileStream fs = new FileStream(@"D:\Excel2003.xls", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取流 POIFSFileSystem ps = new POIFSFileSystem(fs);//需using NPOI.POIFS.FileSystem; IWorkbook workbook = new HSSFWorkbook(ps); ISheet sheet = workbook.GetSheetAt(0);//获取工作表 IRow row = sheet.GetRow(0); //得到表头 FileStream fout = new FileStream(@"D:\Excel2003.xls", FileMode.Open, FileAccess.Write, FileShare.ReadWrite);//写入流 row = sheet.CreateRow((sheet.LastRowNum + 1));//在工作表中添加一行 ICell cell1 = row.CreateCell(0); cell1.SetCellValue("测试数据");//赋值 fout.Flush(); workbook.Write(fout);//写入文件 workbook = null; fout.Close(); System.Console.ReadKey(); }