wpf datagrid数据 导出到excel

本文介绍了一种使用C#将DataGrid数据导出到Excel 97-2003格式(.xls)的方法。通过创建HSSFWorkbook并设置样式,可以自定义列宽和表头样式,然后遍历DataGrid的数据项进行填充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void ExportToExcel(DataGrid dataGridView1, string sheetName)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Filter = “Excel(97-2003)|*.xls”;
if (fileDialog.ShowDialog() == false)
{
return;
}
//不允许dataGridView显示添加行,负责导出时会报最后一行未实例化错误
//dataGridView1.AllowUserToAddRows = false;
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);
sheet.SetColumnWidth(0, 20 * 256);//设置宽
sheet.SetColumnWidth(1, 30 * 256);//设置宽
sheet.SetColumnWidth(2, 50 * 256);//设置宽
sheet.SetColumnWidth(3, 20 * 256);//设置宽
IRow rowHead = sheet.CreateRow(0);
ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.FillPattern = FillPattern.SolidForeground;
headStyle.VerticalAlignment= NPOI.SS.UserModel.VerticalAlignment.Top;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
headStyle.FillForegroundColor = 44;
headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
headStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
headStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
headStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
//填写表头
for (int i = 1; i < dataGridView1.Columns.Count; i++)
{
rowHead.CreateCell(i-1, CellType.String).SetCellValue(dataGridView1.Columns[i].Header.ToString());
rowHead.GetCell(i - 1).CellStyle = headStyle;

        }
        //填写内容
        for (int i = 0; i < dataGridView1.Items.Count; i++)
        {
            IRow row = sheet.CreateRow(i + 1);
            DataRowView selectItem = dataGridView1.Items[i] as DataRowView;
            for (int j = 1; j < 5; j++)
            {
                row.CreateCell(j-1, CellType.String).SetCellValue(selectItem.Row[(j==3?9:j)].ToString());
            }
        }

        try
        {
            using (FileStream stream = File.OpenWrite(fileDialog.FileName))
            {
                workbook.Write(stream);
                stream.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            GC.Collect();
            return;
        }
      
        MessageBox.Show("导出数据成功!");
        GC.Collect();
    }
wpf中,可以使用Microsoft.Office.Interop.Excel库来实现将DataGrid中的数据导出Excel文件的功能。首先,我们需要创建一个新的Excel应用程序实例,并且添加一个工作簿和工作表。接着,我们可以利用DataGrid中的数据来填充Excel表格,并设置单元格的格式和样式。最后,我们需要保存这个工作簿为一个Excel文件,并关闭Excel应用程序实例。以下是一个简单的示例代码: ```csharp private void ExportToExcel(DataGrid dataGrid, string filePath) { Microsoft.Office.Interop.Excel._Application excelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel._Workbook workbook = excelApp.Workbooks.Add(Type.Missing); Microsoft.Office.Interop.Excel._Worksheet worksheet = null; try { // 获取DataGrid中的列数和行数 int columnsCount = dataGrid.Columns.Count; int rowsCount = dataGrid.Items.Count; worksheet = workbook.ActiveSheet; // 将DataGrid中的数据填充到Excel表格中 for (int i = 0; i < columnsCount; i++) { worksheet.Cells[1, i + 1] = dataGrid.Columns[i].Header; for (int j = 0; j < rowsCount; j++) { worksheet.Cells[j + 2, i + 1] = ((TextBlock)dataGrid.Columns[i].GetCellContent(dataGrid.Items[j])).Text; } } // 保存工作簿为Excel文件 workbook.SaveAs(filePath); } catch (Exception ex) { // 处理异常 } finally { // 关闭Excel应用程序实例 excelApp.Quit(); workbook = null; worksheet = null; } } ``` 需要注意的是,由于这里使用了Interop库,所以需要确保目标机器上安装了Excel应用程序。另外,导出数据量较大时需要注意性能问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值