0
我使用SQL查詢獲取datagridview
中的數據。然後我將數據導出爲excel。 當我點擊按鈕,我完全得到的數據爲datagridview
,我可以導出並保存第一批數據。如何將新的datagridview數據導出爲excel
當我要導出到新的數據到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();
}
這聽起來像你需要保持一個計數或最後一行的位置,並開始你的循環在這個數字而不是0,這樣你就不會覆蓋上一次按鈕點擊完成了什麼。 – Crowcoder
使用'worksheet.UsedRange.Rows.Count'作爲最後一排位置 –
@AzarShaikh我應該在我的代碼中使用它? – TolgaKucuk