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文件.
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
asp.net Request.ServerVariables[] 讀解
asp.net Request.ServerVariables[] 讀解,學(xué)習(xí).net的朋友可以參考下,方便獲取服務(wù)器的一些信息。2011-08-08
asp.net4.0框架下驗(yàn)證機(jī)制失效的原因及處理辦法
asp.net4.0框架下驗(yàn)證機(jī)制失效的原因及處理辦法,需要的朋友可以參考一下2013-06-06
一個(gè)ASP.Net下的WebShell實(shí)例
一個(gè)ASP.Net下的WebShell,主要完成cmd命令。一般的服務(wù)器設(shè)置,asp.net用戶的權(quán)限都比較高。如果asp的webshell無法執(zhí)行,可能asp.net的可以執(zhí)行。2013-07-07
Entity Framework使用Code First模式管理事務(wù)
本文詳細(xì)講解了Entity Framework使用Code First模式管理事務(wù)的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03
SQL Server數(shù)據(jù)庫連接 Web.config如何配置
以下的文章主要描述的是Web.config正確配置SQL Server數(shù)據(jù)庫連接的實(shí)際擦步驟。我們以圖文結(jié)合的方式對(duì)其有個(gè)更好的說明,需要的朋友可以參考下2015-10-10
.NET Core對(duì)象池的應(yīng)用:編程篇
對(duì)象池就是對(duì)象的容器,旨在優(yōu)化資源的使用,通過在一個(gè)容器中池化對(duì)象,并根據(jù)需要重復(fù)使用這些池化對(duì)象來滿足性能上的需求。這篇文章主要介紹了.NET Core對(duì)象池的應(yīng)用,感興趣的小伙伴可以參考一下2021-09-09

