WinForm中預(yù)覽Office文件的方法-創(chuàng)新互聯(lián)

小編給大家分享一下WinForm中預(yù)覽Office文件的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比普陀網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式普陀網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋普陀地區(qū)。費(fèi)用合理售后完善,十載實(shí)體公司更值得信賴。

WinForm預(yù)覽Office文檔的方法,具體內(nèi)容如下


使用WinForm, WPF, Office組件

原理:使用Office COM組件將Word,Excel轉(zhuǎn)換為XPS文檔, 將WPF的DocumentViewer控件寄宿到WinForm中, 實(shí)現(xiàn)預(yù)覽.

1. 新建WinForm項(xiàng)目

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

WinForm中預(yù)覽Office文件的方法

3. 編輯WPF用戶控件

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

VS設(shè)計(jì)預(yù)覽顯示效果如下:

WinForm中預(yù)覽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中預(yù)覽Office文件的方法

在WinForm上添加ElementHost

WinForm中預(yù)覽Office文件的方法

將WPF用戶控件添加到ElementHost上,設(shè)計(jì)器代碼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后臺(tái)代碼中定義方法:

  /// <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類似)轉(zhuǎn)換為XPS文件

通過Nuget包管理控制臺(tái)安裝COM組件:

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


轉(zhuǎn)換為XPS:

  /// <summary>
  /// 將Excel文件轉(zhuǎn)換為XPS文件
  /// </summary>
  /// <param name="execelFileName">Excel文件名</param>
  /// <param name="xpsFileName">轉(zhuǎn)換的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);
  }

擴(kuò)展: 每次調(diào)用Excel打開文件,均會(huì)產(chǎn)生一個(gè)進(jìn)程, 在網(wǎng)絡(luò)上收集的釋放Excel進(jìn)程方式均不起作用. 因此選擇直接結(jié)束進(jìn)程, 根據(jù)Excel句柄結(jié)束進(jìn)程, 而不是根據(jù)進(jìn)程名稱殺死全部正在運(yùn)行的Excel.

  [DllImport("User32.dll")]
  private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);

  /// <summary>
  /// 結(jié)束Excel進(jìn)程
  /// </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 { }
  }

現(xiàn)在已經(jīng)可以正常的預(yù)覽Excel文件了. 由于Excel另存為XPS文件會(huì)耗費(fèi)一定的時(shí)間, 因此建議在后臺(tái)線程中提前異步生成, 在預(yù)覽時(shí)可直接調(diào)取XPS文件.

以上是“WinForm中預(yù)覽Office文件的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

分享標(biāo)題:WinForm中預(yù)覽Office文件的方法-創(chuàng)新互聯(lián)
文章地址:http://muchs.cn/article22/pspjc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、關(guān)鍵詞優(yōu)化、云服務(wù)器企業(yè)建站、App開發(fā)手機(jī)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化