0

我正在使用 C# Windows 应用程序。尝试将数据从 gridview 导出到 Excel ,但是当 gridview 列为空时,我确实收到错误消息。

如何处理?请帮忙

这是我的代码

        // Store Header from Gridview to Excel
        for (int i = 1; i < dgvresult.Columns.Count + 1; i++)
        {
            Excel.Cells[1, i] = dgvresult.Columns[i - 1].HeaderText;
        }

        // Loop rows and columns of Gridview to store to Excel

        for (int i = 0; i < dgvresult.Rows.Count; i++)
        {
            for (int j = 0; j < dgvresult.Columns.Count; j++)
            {
                Excel.Cells[i + 2, j + 1] = dgvresult.Rows[i].Cells[j].Value.ToString(); // Here when the value in Gridview is empty error how to handle this
            }
        }

        Excel.ActiveWorkbook.SaveCopyAs("D:\\Asserts.xls");
        Excel.ActiveWorkbook.Saved = true;
        Excel.Quit();

        MessageBox.Show("Excel file created,you can find the file D:\\Asserts.xls");
        Excel.Visible = true;
4

1 回答 1

0

找到解决方案通过下面的代码进行检查

    private void btnexport_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.ApplicationClass Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
        Excel.Application.Workbooks.Add(Type.Missing);
        Excel.Columns.ColumnWidth = 14;

        // Store Header from Gridview to Excel
        for (int i = 1; i < dgvresult.Columns.Count + 1; i++)
        {
            Excel.Cells[1, i] = dgvresult.Columns[i - 1].HeaderText;
        }

        // Loop rows and columns of Gridview to store to Excel

        for (int i = 0; i < dgvresult.Rows.Count; i++)
        {
            for (int j = 0; j < dgvresult.Columns.Count; j++)
            {
                if (dgvresult.Rows[i].Cells[j].Value == null)
                {
                    dgvresult.Rows[i].Cells[j].Value = "NA"; // Where the gridview is empty do a checking and Insert NA 
                }


                Excel.Cells[i + 2, j + 1] = dgvresult.Rows[i].Cells[j].Value.ToString();
            }
        }

        Excel.ActiveWorkbook.SaveCopyAs("D:\\Asserts.xls");
        Excel.ActiveWorkbook.Saved = true;
        Excel.Quit();
        MessageBox.Show("Excel file created,you can find the file D:\\Asserts.xls");
        Excel.Visible = true;

    }
于 2013-09-21T13:13:44.060 回答