根据每次写入的数据增加excel单元格

目前我必须指定要添加的值的单元格。 我怎么喜欢以某种方式增加,就像无论用户点击添加到文件button多less次,它应该增加以前的模式。 例如。 我有 :

xlWorkSheet.Cells[1, 1] = comboBox2.Text; xlWorkSheet.Cells[1, 2] = textBox5.Text; xlWorkSheet.Cells[1, 3] = textBox2.Text; xlWorkSheet.Cells[1, 4] = comboBox3.Text; xlWorkSheet.Cells[1, 5] = textBox3.Text; xlWorkSheet.Cells[1, 6] = comboBox1.Text; 

点击“添加到xls文件”button,我将如何使它现在遵循这个模式,并保存到文件,而不必写入代码:

  xlWorkSheet.Cells[2, 1] = comboBox2.Text; xlWorkSheet.Cells[2, 2] = textBox5.Text; xlWorkSheet.Cells[2, 3] = textBox2.Text; xlWorkSheet.Cells[2, 4] = comboBox3.Text; xlWorkSheet.Cells[2, 5] = textBox3.Text; xlWorkSheet.Cells[2, 6] = comboBox1.Text; 

这不像我可以复制和粘贴每一次,这将是太繁琐。 所有的答案和评论都欢迎。 提前致谢

你可以使用财产。

 public int IndexProp {get; set;} public void AddToExcelBtn_Click(object sender, EventArgs e) { //... some other code Index +=1; xlWorkSheet.Cells[IndexProp , 1] = comboBox2.Text; xlWorkSheet.Cells[IndexProp , 2] = textBox5.Text; xlWorkSheet.Cells[IndexProp , 3] = textBox2.Text; xlWorkSheet.Cells[IndexProp , 4] = comboBox3.Text; xlWorkSheet.Cells[IndexProp , 5] = textBox3.Text; xlWorkSheet.Cells[IndexProp , 6] = comboBox1.Text; } 

这是基于以前的答案,但更容易看到,并将打开文件重置您的索引。 如果每个组合或文本框都有一个button,则需要添加更多标识符。

 public static int indexProp = 0; public void OpenExcelFile(string path){ //Open new file here indexProp = 0; //reset value as needed } public void AddToExcelBtn_Click(object sender, EventArgs e) { //... some other code indexProp +=1; xlWorkSheet.Cells[indexProp , 1] = comboBox2.Text; xlWorkSheet.Cells[indexProp , 2] = textBox5.Text; xlWorkSheet.Cells[indexProp , 3] = textBox2.Text; xlWorkSheet.Cells[indexProp , 4] = comboBox3.Text; xlWorkSheet.Cells[indexProp , 5] = textBox3.Text; xlWorkSheet.Cells[indexProp , 6] = comboBox1.Text; 

}

您不必打开工作簿即可写入。 有像OpenXML和ADO.NET这样的技术可以像数据库一样处理和操纵信息。 OpenXML有一个陡峭的学习曲线,所以我会尝试ADO.NET,如果它可以在您的networking上工作。

互操作打开文件,你将不得不使用单元格或外部文本文件来检索数字。

在另一个说明中,我假设你正在谈论添加数据的幕后VBA。 如果你追加数据,你所要做的就是从底部开始。

 lastRow = valWkSht.Range("B65535").End(xlUp).Row