WPF 根据Word模版导出数据到Word

WPF 根据Word模版导出数据到Word

前台.xaml文件:

<Window x:Class="Export.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Height="23" HorizontalAlignment="Left" Margin="24,22,0,0" Name="textBox1" VerticalAlignment="Top" Width="322" />
        <Button Content="Choose Stencil File" Height="23" HorizontalAlignment="Left" Margin="360,22,0,0" Name="button2" VerticalAlignment="Top" Width="131" Click="button2_Click" />
        <Button Content="Export To Word" Height="44" HorizontalAlignment="Left" Margin="199,107,0,0" Name="ExportDoc" VerticalAlignment="Top" Width="100" Click="ExportDoc_Click" />
        <Button Content="GetThumbnailsImage" Height="57" HorizontalAlignment="Left" Margin="160,228,0,0" Name="Thumbnails" VerticalAlignment="Top" Width="139" Click="Thumbnails_Click" />
    </Grid>
</Window>

后台.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用以下步骤将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(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值