WinForm中如何預(yù)覽Office文件
本文為大家分享了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控件

3. 編輯WPF用戶控件
<UserControl ...
...>
<Grid>
<DocumentViewer x:Name="documentViewer"/>
</Grid>
</UserControl>
VS設(shè)計(jì)預(yù)覽顯示效果如下:

如果不需要自帶的工具欄, 可以添加以下資源隱藏工具欄:
<!--隱藏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上添加ElementHost

將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文件.
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
aspx文件格式使用URLRewriter實(shí)現(xiàn)靜態(tài)化變成html
如何隱藏aspx文件格式,變成html,使用asp.net 開發(fā)的網(wǎng)頁程序,使用URLRewriter.dll 實(shí)現(xiàn)靜態(tài)化,接下來將介紹下具體操作步驟,感興趣的朋友可以參考下2013-04-04
.NET一行代碼實(shí)現(xiàn)GC調(diào)優(yōu),讓程序不再占用內(nèi)存
這篇文章主要介紹了NET一行代碼實(shí)現(xiàn)GC調(diào)優(yōu),讓程序不再占用內(nèi)存的相關(guān)資料,需要的朋友可以參考下2022-11-11
relaxlife.net發(fā)布一個(gè)自己開發(fā)的中文分詞程序
relaxlife.net發(fā)布一個(gè)自己開發(fā)的中文分詞程序...2007-03-03
ASP.NET設(shè)計(jì)網(wǎng)絡(luò)硬盤之文件夾實(shí)現(xiàn)
ASP.NET設(shè)計(jì)網(wǎng)絡(luò)硬盤之文件夾實(shí)現(xiàn)...2006-09-09
asp.net mvc4 mysql制作簡(jiǎn)單分頁組件(部分視圖)
這篇文章主要介紹了asp.net mvc4 mysql制作簡(jiǎn)單分頁組件,附部分視圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10

