C# DataGrid整行写入EXCEL
时间: 2023-07-12 21:04:20 浏览: 131
以下是将DataGrid中的所有行写入Excel文件的C#代码示例:
```csharp
private void ExportToExcel(DataGridView dataGridView)
{
// 创建Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
int StartCol = 1;
int StartRow = 1;
int j = 0, i = 0;
// 将DataGridView中的列标题写入Excel文件
for (j = 0; j < dataGridView.Columns.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
myRange.Value2 = dataGridView.Columns[j].HeaderText;
}
// 将DataGridView中的每一行数据写入Excel文件
for (i = 0; i < dataGridView.Rows.Count; i++)
{
for (j = 0; j < dataGridView.Columns.Count; j++)
{
try
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + 1 + i, StartCol + j];
myRange.Value2 = dataGridView[j, i].Value == null ? "" : dataGridView[j, i].Value.ToString();
}
catch
{
MessageBox.Show("Error");
}
}
}
//设置禁止弹出保存和覆盖的询问提示框
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
//保存工作簿
workbook.SaveAs("D:\\ExcelFile.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, false,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
//释放对象
workbook.Close(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet1);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
sheet1 = null;
workbook = null;
excel = null;
GC.Collect();
}
```
在上面的代码中,我们创建了一个Excel对象并使用它来写入DataGridView中的所有行。首先,我们将DataGridView中的列标题写入Excel文件,然后将每一行数据写入Excel文件。最后,我们将Excel文件保存到本地磁盘,并清理Excel对象以释放内存。
阅读全文