WPF中DataGrid的数据导出到Excel
时间: 2023-10-10 12:12:04 浏览: 150
可以使用以下步骤将WPF中DataGrid的数据导出到Excel:
1. 添加对Microsoft.Office.Interop.Excel的引用。可以在项目中通过右键点击“引用”->“添加引用”来添加。
2. 创建一个新的Excel应用程序对象:
```
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApp = new Excel.Application();
```
3. 创建一个工作簿对象并添加一个新工作表:
```
Excel.Workbook workbook = excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.ActiveSheet;
worksheet.Name = "DataGrid数据";
```
4. 将DataGrid中的数据复制到Excel表格中:
```
for (int i = 0; i < dataGrid.Items.Count; i++)
{
for (int j = 0; j < dataGrid.Columns.Count; j++)
{
var cellValue = dataGrid.Columns[j].GetCellContent(dataGrid.Items[i]);
if (cellValue != null)
{
worksheet.Cells[i + 1, j + 1] = cellValue.ToString();
}
}
}
```
5. 保存Excel文件并关闭Excel应用程序对象:
```
workbook.SaveAs("DataGrid数据.xlsx");
workbook.Close();
excelApp.Quit();
```
完整代码示例如下:
```
private void ExportToExcel(DataGrid dataGrid)
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Add();
Excel.Worksheet worksheet = workbook.ActiveSheet;
worksheet.Name = "DataGrid数据";
for (int i = 0; i < dataGrid.Items.Count; i++)
{
for (int j = 0; j < dataGrid.Columns.Count; j++)
{
var cellValue = dataGrid.Columns[j].GetCellContent(dataGrid.Items[i]);
if (cellValue != null)
{
worksheet.Cells[i + 1, j + 1] = cellValue.ToString();
}
}
}
workbook.SaveAs("DataGrid数据.xlsx");
workbook.Close();
excelApp.Quit();
}
```
阅读全文