一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

WinForm中如何预览Office文件

时间:2017-10-23 编辑:猪哥 来源:一聚教程网

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

使用WinForm, WPF, Office组件

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

1. 新建WinForm项目

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

3. 编辑WPF用户控件


  
    
  

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

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



  

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后台代码中定义方法:

  /// 
  /// 加载XPS文件
  /// 
  /// XPS文件名
  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:

  /// 
  /// 将Excel文件转换为XPS文件
  /// 
  /// Excel文件名
  /// 转换的xps文件名
  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);

  /// 
  /// 结束Excel进程
  /// 
  /// 
  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文件.

热门栏目