WinForm中預覽Office文件

WinForm預覽Office文檔

使用WinForm, WPF, Office組件網絡

原理:使用Office COM組件將Word,Excel轉換爲XPS文檔, 將WPF的DocumentViewer控件寄宿到WinForm中, 實現預覽.app

1. 新建WinForm項目

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

3. 編輯WPF用戶控件

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

VS設計預覽顯示效果以下:異步

若是不須要自帶的工具欄, 能夠添加如下資源隱藏工具欄:工具

<!--隱藏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上添加ElementHostui

將WPF用戶控件添加到ElementHost上,設計器代碼XpsPreviewer.Designer.cs以下this

//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:excel

/// <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.code

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

補充: Word 轉換爲 PDF

Word.Application app = new Word.Application();
    Word.Document document = null;
    object missing = System.Reflection.Missing.Value;
    app.Visible = false;
    document = app.Documents.Open(sourcePath);
    document.ExportAsFixedFormat(targetPath, Word.WdExportFormat.wdExportFormatPDF);
    object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
    document.Close(ref saveChanges, ref missing, ref missing);
    ((Word._Application)app).Quit(ref missing, ref missing, ref missing);
相關文章
相關標籤/搜索