将datagrid导出到Excel标题但没有行

时间:2017-09-13 16:39:39

标签: c# excel datagridview

它导出标题确定但没有导出任何行。目前有2列,只有2行试图导出。

我认为我的循环中有问题,但我没有看到它。

寻找一双新鲜的眼睛。

    private void btnExport_Click(object sender, EventArgs e)
    {
        // Creating a Excel object. 
        Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

        try
        {
            worksheet = workbook.ActiveSheet;
            worksheet.Name = "ExportedFromDatGrid";

            int cellRowIndex = 1;
            int cellColumnIndex = 1;

            //Loop through each row and read value from each column. 
            for (int i = 0; i < DGV.Rows.Count; i++)
            {
                for (int j = 0; j < DGV.Columns.Count; j++)
                {
                    if (cellRowIndex == 1)
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = DGV.Columns[j].HeaderText;
                    }
                    else
                    {
                        worksheet.Cells[cellRowIndex, cellColumnIndex] = DGV.Rows[i].Cells[j].Value.ToString();
                    }
                    cellColumnIndex++;
                }
                cellColumnIndex = 1;
                cellRowIndex++;
            }

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
            saveDialog.FilterIndex = 2;

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                workbook.SaveAs(saveDialog.FileName);
                MessageBox.Show("Export Successful");
            }
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            excel.Quit();
            workbook = null;
            excel = null;
        }
    }

1 个答案:

答案 0 :(得分:0)

您希望为列提供单独的循环:

        for (int j = 0; j < DGV.Columns.Count; j++)
        {

            worksheet.Cells[cellRowIndex, cellColumnIndex] = DGV.Columns[j].HeaderText;
            cellColumnIndex++;
        }
        cellRowIndex++;

        //Loop through each row and read value from each column. 
        for (int i = 0; i < DGV.Rows.Count; i++)
        {
            for (int j = 0; j < DGV.Columns.Count; j++)
            {
                worksheet.Cells[cellRowIndex, cellColumnIndex] = DGV.Rows[i].Cells[j].Value.ToString();
                cellColumnIndex++;
            }
            cellColumnIndex = 1;
            cellRowIndex++;
        }