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

使用WinForm, WPF, Office组件

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

1. 新建WinForm项目

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

WinForm中如何预览Office文件

3. 编辑WPF用户控件

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

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

WinForm中如何预览Office文件

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

<!--隐藏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中如何预览Office文件

在WinForm上添加ElementHost

WinForm中如何预览Office文件

将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文件.

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

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。