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



目前我必须指定要添加值的单元格。我怎么喜欢某种方式的增量,不管用户点击多少次添加到文件按钮,它应该只增加之前的模式。如。我有:

        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文件"按钮后,我如何使它现在遵循这个模式并保存到文件,而不必将其写入代码:

        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;

我不可能每次都复制粘贴,那样太繁琐了。欢迎所有的答案和评论。提前感谢

可以使用property。

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;
}

这是基于前面的答案,但是更容易看到,并且会在文件打开时重置索引。如果每个组合或文本框都有一个按钮,则需要在。

中添加进一步的标识符。
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是否能在你的网络上工作。

互操作打开文件,您必须使用单元格或外部文本文件来检索号码。

另一方面,我假设您在幕后谈论的是添加数据的VBA。如果你添加数据,你所需要做的就是从底部开始。

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

最新更新