侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

WinForm中如何预览Office文件

Windows  /  管理员 发布于 5年前   351

本文为大家分享了WinForm预览Office文档的方法,供大家参考,具体内容如下

使用WinForm, WPF, Office组件

原理:使用Office COM组件将Word,Excel转换为XPS文档, 将WPF的DocumentViewer控件寄宿到WinForm中, 实现预览.

1. 新建WinForm项目

2. 新建WPF用户控件, 注意是WPF控件

3. 编辑WPF用户控件

<UserControl ...       ...>  <Grid>    <DocumentViewer x:Name="documentViewer"/>  </Grid></UserControl>

VS设计预览显示效果如下:

如果不需要自带的工具栏, 可以添加以下资源隐藏工具栏:

<!--隐藏DocumentViewer边框--><UserControl.Resources>  <Style x:Key="{x:Type DocumentViewer}" TargetType="{x:Type DocumentViewer}">    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" />    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />    <Setter Property="FocusVisualStyle" Value="{x:Null}" />    <Setter Property="Template">      <Setter.Value>        <ControlTemplate TargetType="{x:Type DocumentViewer}">          <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Focusable="False">            <Grid KeyboardNavigation.TabNavigation="Local">              <Grid.Background>                <SolidColorBrush Color="{DynamicResource ControlLightColor}" />              </Grid.Background>              <Grid.RowDefinitions>                <RowDefinition Height="Auto" />                <RowDefinition Height="*" />                <RowDefinition Height="Auto" />              </Grid.RowDefinitions>              <ScrollViewer Grid.Row="1" CanContentScroll="true" HorizontalScrollBarVisibility="Auto" x:Name="PART_ContentHost" IsTabStop="true">                <ScrollViewer.Background>                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">                    <GradientStop Color="{DynamicResource ControlLightColor}" Offset="0" />                    <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="1" />                  </LinearGradientBrush>                </ScrollViewer.Background>              </ScrollViewer>            </Grid>          </Border>        </ControlTemplate>      </Setter.Value>    </Setter>  </Style></UserControl.Resources>

4. 新建WinForm用户控件

在WinForm上添加ElementHost

将WPF用户控件添加到ElementHost上,设计器代码XpsPreviewer.Designer.cs如下

  //ElementHost  private System.Windows.Forms.Integration.ElementHost elementHost1;  //XpsPreviewer变量  private WPF.XpsPreviewer xpsPreviewer1;  private void InitializeComponent()  {    this.elementHost1 = new System.Windows.Forms.Integration.ElementHost();    this.xpsPreviewer1 = new WPF.XpsPreviewer();    //初始化    //其他属性初始化...    this.elementHost1.Child = this.xpsPreviewer1;    //其他属性初始化...  }

在XpsPreviewer.cs后台代码中定义方法:

  /// <summary>  /// 加载XPS文件  /// </summary>  /// <param name="fileName">XPS文件名</param>  internal void LoadXps(string fileName)  {    var xpsDocument = new XpsDocument(fileName, FileAccess.Read);    this.xpsPreviewer1.documentViewer.Document = xpsDocument.GetFixedDocumentSequence();    xpsDocument.Close();  }

5. 将Excel(Word类似)转换为XPS文件

通过Nuget包管理控制台安装COM组件:

PM> Install-Package Microsoft.Office.Interop.Excel

转换为XPS:

  /// <summary>  /// 将Excel文件转换为XPS文件  /// </summary>  /// <param name="execelFileName">Excel文件名</param>  /// <param name="xpsFileName">转换的xps文件名</param>  public void ConvertExcelToXps(string excelFileName, string xpsFileName)  {    if (string.IsNullOrWhiteSpace(excelFileName))      throw new ArgumentNullException(excelFileName);    if (string.IsNullOrWhiteSpace(xpsFileName))      throw new ArgumentNullException(xpsFileName);    var fileInfo = new FileInfo(xpsFileName);    if (!fileInfo.Directory.Exists)      fileInfo.Directory.Create();    //删除已存在的文件    if (File.Exists(xpsFileName))      File.Delete(xpsFileName);    Excel.Application app = new Excel.Application();    app.DisplayAlerts = false;    Excel.Workbooks wbs;    Excel.Workbook wb;    wbs = app.Workbooks;    wb = wbs.Add(excelFileName);    dynamic Nothing = System.Reflection.Missing.Value;    wb.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypeXPS, xpsFileName, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);    wb.Close(true);    wbs.Close();    app.Quit();    KillExcelProcess(app);  }

扩展: 每次调用Excel打开文件,均会产生一个进程, 在网络上收集的释放Excel进程方式均不起作用. 因此选择直接结束进程, 根据Excel句柄结束进程, 而不是根据进程名称杀死全部正在运行的Excel.

  [DllImport("User32.dll")]  private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);  /// <summary>  /// 结束Excel进程  /// </summary>  /// <param name="obj"></param>  private void KillExcelProcess(Excel.Application app)  {    if (app == null)      return;    try    {      IntPtr intptr = new IntPtr(app.Hwnd);      int id;      GetWindowThreadProcessId(intptr, out id);      var p = Process.GetProcessById(id);      p.Kill();    }    catch { }  }

现在已经可以正常的预览Excel文件了. 由于Excel另存为XPS文件会耗费一定的时间, 因此建议在后台线程中提前异步生成, 在预览时可直接调取XPS文件.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    使用重绘项美化WinForm的控件
    下一条:
    使用Topshelf组件构建简单的Windows服务
  • 昵称:

    邮箱:

    1条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Windows 10的告别:2025年10月14日,一段时代的终结(0个评论)
    • windows 11激活_Win11 KMS激活流程步骤(1个评论)
    • 安装Windows 11系统的注意了,看看你的cpu是否在微软兼容列表排除中(1个评论)
    • 微软将于2022年9月20日推送Windows11 22H2新版本,推测2024发布windows 12(0个评论)
    • windows11系统中可以关闭禁止的服务及介绍(1个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2018-01
    • 2018-06
    • 2020-06
    • 2021-06
    • 2021-07
    • 2022-01
    • 2022-04
    • 2022-08
    • 2023-08
    • 2023-10
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客