如何将新的datagridview数据导出为ex​​cel

我正在用SQL查询获取datagridview中的datagridview 。 然后我将数据导出为ex​​cel。 当我点击button,我得到的数据datagridview完美,我可以导出和保存第一个数据为Excel。

当我想导出到新的数据,我不能这样做,我已经保存的数据

例如; 我保存了10行数据,然后当我想保存20行数据时,它应该是30行数据,但我有20行数据

我该如何解决?

这里是我的代码导出到Excel中:

 private void bttn_Excel_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel._Worksheet worksheet = null; app.Visible = true; worksheet = workbook.Sheets["Sayfa1"]; worksheet = workbook.ActiveSheet; worksheet.Name = "Anlık Değerleri"; // storing header part in Excel for (int i = 1; i < dataGridView1.Columns.Count + 1; i++) { worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText; } // storing Each row and column value to excel sheet for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { for (int j = 0; j < dataGridView1.Columns.Count; j++) { worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString(); } } // save the application workbook.SaveAs("C:\\Users\\senerk\\Desktop\\Kitap1.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // Exit from the application app.Quit(); } 

As Azar Shaikh提到你应该使用worksheet.UsedRange.Rows.Count 。 改变你的第二个循环到这个,它应该工作:

 for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { for (int j = 0; j < dataGridView1.Columns.Count; j++) { worksheet.Cells[worksheet.UsedRange.Rows.Count + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString(); } } 

我没有在工作环境中进行testing,但是你明白了! 更多信息在这里 。