how to export new datagridview datas to excel

时间:2017-08-04 12:27:24

标签: c# excel datagridview

I am getting data in datagridview with a SQL query. Then I'm exporting the data to excel. When I click the button I get the data to datagridview perfectly and I can export and save the first data to excel.

When I want to export to new data to excel I cannot do that on the data I have saved

For example; I saved 10 rows of data and then when I want to save 20 rows of data it should be 30 rows data on excel but I have 20 rows of data

How can I fix it?

Here is my code to export to 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();
 }

1 个答案:

答案 0 :(得分:1)

Asar 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();
    }
}

我没有在工作环境中测试它,但你明白了! 更多信息here