[英]NPOI Insert/append value to .xls file
將數據追加到現有的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();
希望它能解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.