NPOI插入/追加值到.xls文件
我有问题追加数据到现有的Excel文件。
这里是代码:
HSSFWorkbook hssfwb; FileStream file1 = new FileStream(pathDoXls, FileMode.Open, FileAccess.Read); hssfwb = new HSSFWorkbook(file1); ISheet sheet = hssfwb.GetSheet("Zawodnicy"); int ostatniWiersz = sheet.LastRowNum; textBox14.Text = (ostatniWiersz+1).ToString(); Console.WriteLine(ostatniWiersz); ICell cell = sheet.CreateRow(ostatniWiersz+1).CreateCell(0); cell.SetCellValue(textBox14.Text); ICell cell1 = sheet.CreateRow(ostatniWiersz + 1).CreateCell(1); cell1.SetCellValue(textBox2.Text); //sheet.CreateRow(ostatniWiersz + 1).CreateCell(1).SetCellValue(textBox2.Text); //sheet.CreateRow(ostatniWiersz + 1).CreateCell(2).SetCellValue(textBox3.Text); FileStream file = new FileStream(pathDoXls, FileMode.Create); hssfwb.Write(file); file.Close();
理论上这部分代码:
ICell cell = sheet.CreateRow(ostatniWiersz+1).CreateCell(0); cell.SetCellValue(textBox14.Text); ICell cell1 = sheet.CreateRow(ostatniWiersz + 1).CreateCell(1); cell1.SetCellValue(textBox2.Text);
应该在最后一排位置创build单元格,我的意思是:
ostatniWiersz=10
所以在第11行和第0格应该是textBox14内容在第11行的单元格1应该是textBox2的内容。
但是当我编译这个代码时,我只有在第11行的单元格中有值。理论上的值应该插入在两个字段(我指的是单元格0和1)
感谢帮助。
你正在覆盖同一行,这就是为什么下面的代码效果丢失了
ICell cell = sheet.CreateRow(ostatniWiersz+1).CreateCell(0); cell.SetCellValue(textBox14.Text);
尝试使用下面的代码。
HSSFWorkbook hssfwb; FileStream file1 = new FileStream(pathDoXls, FileMode.Open, FileAccess.Read); hssfwb = new HSSFWorkbook(file1); ISheet sheet = hssfwb.GetSheet("Zawodnicy"); int ostatniWiersz = sheet.LastRowNum; textBox14.Text = (ostatniWiersz + 1).ToString(); Console.WriteLine(ostatniWiersz); IRow worksheetRow = sheet.CreateRow(ostatniWiersz + 1); ICell cell = worksheetRow.CreateCell(0); cell.SetCellValue(textBox14.Text); ICell cell1 = worksheetRow.CreateCell(1); cell1.SetCellValue(textBox2.Text); //sheet.CreateRow(ostatniWiersz + 1).CreateCell(1).SetCellValue(textBox2.Text); //sheet.CreateRow(ostatniWiersz + 1).CreateCell(2).SetCellValue(textBox3.Text); FileStream file = new FileStream(pathDoXls, FileMode.Create); hssfwb.Write(file); file.Close();
希望它能解决你的问题。