【发布时间】:2011-12-29 11:28:01
【问题描述】:
在我的应用程序中,需要将 datagridview 导出到 Excel 中。
我正在使用以下源代码。我想就以下问题寻求专家建议。
我的代码是否正确?因为我没有在所选路径中保存任何文件。
从网格导出数据时是否存在任何性能问题,因为网格中可能有尽可能多的可用数据?
- 我正在使用命名空间“Microsoft.Office.Interop.Excel”,不确定是否正确?
private void btnSaveResult_Click(object sender, EventArgs e)
{
try
{
if (this.saveFileDialog.ShowDialog() == DialogResult.OK)
{
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 30;
for (int i = 0; i < grdResult.Rows.Count; i++)
{
DataGridViewRow row = grdResult.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("The Save button was clicked or the Enter key was pressed" + "\nThe file would have been saved as " + this.saveFileDialog.FileName);
}
else MessageBox.Show("The Cancel button was clicked or Esc was pressed");
}
catch (Exception ex)
{
MessageBox.Show("Cancelled Save Operation");
this.Close();
}
}
【问题讨论】:
标签: c# excel datagridview