How to preview Office files in WinForm, and how to preview office in winform

Source: Internet
Author: User

How to preview Office files in WinForm, and how to preview office in winform

This article shares with you how to preview the Office document in WinForm. The content is as follows:

Use WinForm, WPF, and Office Components

Principle: use the Office COM component to convert Word and Excel into XPS documents, and host the WPF DocumentViewer control to WinForm for preview.

1. Create a WinForm Project

2. Create a WPF user control.

3. Edit the WPF User Control

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

VS design preview:

If you do not need a toolbar, you can add the following resource hiding toolbar:

<! -- Hide the DocumentViewer border --> <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. Create a WinForm User Control

Add ElementHost on WinForm

Add the WPF user control to ElementHost. The Designer code is as follows:

// ElementHost 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 (); // initialization of other attributes... this. elementHost1.Child = this. xpsPreviewer1; // initialization of other attributes ...}

In the spreviewer. cs background code, define the method:

/// <Summary> /// load the XPS file /// </summary> /// <param name = "fileName"> XPS file name </param> internal void LoadXps (string fileName) {var xpsDocument = new XpsDocument (fileName, FileAccess. read); this.xpsPreviewer1.doc umentViewer. document = xpsDocument. getFixedDocumentSequence (); xpsDocument. close ();}

5. Convert Excel (similar to Word) to an XPS File

Install the COM component on the Nuget package console:

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

Convert to XPS:

/// <Summary> /// convert an Excel file to an XPS file // </summary> /// <param name = "execelFileName"> Excel file name </param> /// <param name = "xpsFileName"> name of the converted xps file </param> public void ConvertExcelToXps (string excelFileName, string xpsFileName) {if (string. isNullOrWhiteSpace (excelFileName) throw new ArgumentNullException (excelFileName); if (string. isNullOrWhiteSpace (xpsFileName) throw new ArgumentNullException (xpsFileNa Me); var fileInfo = new FileInfo (xpsFileName); if (! FileInfo. directory. exists) fileInfo. directory. create (); // delete an existing File 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); wb. close (true); wbs. close (); app. quit (); KillExcelProcess (app );}

Extension: each time an Excel file is called to open a file, a process is generated, and the Excel process release method collected on the network does not work. therefore, stop the process directly and end the process according to the Excel handle, instead of killing all running Excel files based on the process name.

[DllImport ("User32.dll")] private static extern int GetWindowThreadProcessId (IntPtr hWnd, out int ProcessId ); /// <summary> /// end the Excel process /// </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. getprocpolicyid (id); p. kill () ;}catch {}}

The Excel file can be normally previewed now. Since it takes some time to save the Excel file as An XPS file, we recommend that you generate it asynchronously in the background thread in advance and directly retrieve the XPS file during preview.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.