简体   繁体   English

如果在C#中使用ClosedXML创建数据,则将数据追加到Excel工作表

[英]Append data to excel sheet if created using ClosedXML in c#

I am writing an application in which I need to store data cell values into excel sheet. 我正在编写一个需要将数据单元格值存储到excel工作表中的应用程序。 Everything is working fine but the problem is everytime I run the application, it overwrites the existing data. 一切工作正常,但问题出在我每次运行应用程序时,它都会覆盖现有数据。

So far the code I have taken from Github: 到目前为止,我从Github中获取的代码是:

  var workbook = new XLWorkbook();
  var worksheet = workbook.Worksheets.Add("Sample Sheet");
  worksheet.Cell("A1").Value = this.textBox1.Text;
  worksheet.Cell("B1").Value = this.textBox2.Text;
  worksheet.Cell("C1").Value = this.textBox3.Text;
  worksheet.Cell("D1").Value = col1;
  worksheet.Cell("E1").Value = col2;
  worksheet.Cell("F1").Value = this.textBox6.Text;
  workbook.SaveAs("HelloWorld.xlsx");

Note: I don't want to save data using datatable or anything. 注意:我不想使用数据表或其他任何方式保存数据。 I just want to get values from textboxes and append them to the existing sheet. 我只想从文本框中获取值并将它们附加到现有工作表中。 I have visited many stackoverflow post but they doesn't helped me much. 我访问了许多stackoverflow 帖子,但是它们并没有给我带来太大帮助。

Thanks in advance! 提前致谢!

You are explicitly storing the values in row 1 of the spreadsheet. 您将值明确存储在电子表格的第1行中。 If you want to append the values, you'll have to increment the row number and store the values in the appropriate cells. 如果要附加值,则必须增加行号并将值存储在适当的单元格中。

Hope this helps: 希望这可以帮助:

var wb = new XLWorkbook("Path to file");
IXLWorksheet Worksheet = wb.Worksheet("Tab name");
int NumberOfLastRow = Worksheet.LastRowUsed().RowNumber();
IXLCell CellForNewData = Worksheet.Cell(NumberOfLastRow + 1, 1);

CellForNewData.InsertData(your_data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM