我正在使用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;
答案 0 :(得分: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;
}