我在将数据附加到现有 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);
应该在最后一行位置创建单元格,我的意思是:
ostatniWiersz=10
因此第 11 行和单元格 0 中应该是 textBox14 内容 第 11 行单元格 1 应该是 textBox2 内容。
但是当我编译此代码时,我仅在第 11 行单元格 1 中具有值。理论上,值应该插入到两个字段中(我的意思是单元格 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();
希望能解决您的问题。
关于c# - NPOI 将值插入/附加到 .xls 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725258/