How to preview office files in WinForm


This article shared the WinForm preview office document method for your reference, the specific content is as follows

Using WinForm, WPF, office components

Principle: use office COM component to convert word and Excel to XPS document, and convert WPF toDocumentViewerControl host to WinForm, preview

1. New WinForm project

2. Create a new WPF user control. Pay attention to the WPF control

3. Edit WPF user control

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

The display effect of vs design preview is as follows:

If you don’t need a built-in toolbar, you can add the following resources to hide the toolbar:

<! -- hide documentviewer border -- >
  <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">
        <ControlTemplate TargetType="{x:Type DocumentViewer}">
          <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Focusable="False">
            <Grid KeyboardNavigation.TabNavigation="Local">
                <SolidColorBrush Color="{DynamicResource ControlLightColor}" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
                <RowDefinition Height="Auto" />
              <ScrollViewer Grid.Row="1" CanContentScroll="true" HorizontalScrollBarVisibility="Auto" x:Name="PART_ContentHost" IsTabStop="true">
                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="{DynamicResource ControlLightColor}" Offset="0" />
                    <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="1" />

4. Create a new WinForm user control

Add on WinFormElementHost

Add the WPF user control to the ElementHost and add the designer code XpsPreviewer.Designer.cs as follows

  private System.Windows.Forms.Integration.ElementHost elementHost1;
  //Xpspreviewer variable
  private WPF.XpsPreviewer xpsPreviewer1;

  private void InitializeComponent()
    this.elementHost1 = new System.Windows.Forms.Integration.ElementHost();
    this.xpsPreviewer1 = new WPF.XpsPreviewer();

    //More properties initialization
    this.elementHost1.Child = this.xpsPreviewer1;
    //More properties initialization

stay XpsPreviewer.cs Methods defined in background code:

/// <summary>
  ///Loading XPS file
  /// </summary>
  ///< param name = "file name" > XPS file name < / param >
  internal void LoadXps(string fileName)
    var xpsDocument = new XpsDocument(fileName, FileAccess.Read);
    this.xpsPreviewer1.documentViewer.Document = xpsDocument.GetFixedDocumentSequence();

5. Convert excel (similar to word) to XPS file

To install COM components through nuget package management console:

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


/// <summary>
  ///Converting excel file to XPS file
  /// </summary>
  ///< param name = "execelfile name" > excel file name < / param >
  ///< param name = "xpsfilename" > converted XPS file name < / 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)

    //Delete existing files
    if (File.Exists(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);

Extension: every time excel is called to open a file, a process will be generated. The method of releasing excel process collected on the network does not work. Therefore, you choose to end the process directly and end the process according to the excel handle instead of killing all running excel according to the process name

  private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId);

  /// <summary>
  ///End excel process
  /// </summary>
  /// <param name="obj"></param>
  private void KillExcelProcess(Excel.Application app)
    if (app == null)
      IntPtr intptr = new IntPtr(app.Hwnd);
      int id;
      GetWindowThreadProcessId(intptr, out id);
      var p = Process.GetProcessById(id);
    catch { }

Now the excel file can be previewed normally. Because saving excel as an XPS file will take a certain amount of time, it is recommended to generate it asynchronously in the background thread in advance. When previewing, you can call the XPS file directly

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.