小編給大家分享一下WinForm中預覽Office文件的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

WinForm預覽Office文檔的方法,具體內容如下
使用WinForm, WPF, Office組件
原理:使用Office COM組件將Word,Excel轉換為XPS文檔, 將WPF的DocumentViewer控件寄宿到WinForm中, 實現預覽.
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上添加ElementHost

將WPF用戶控件添加到ElementHost上,設計器代碼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后臺代碼中定義方法:
/// <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:
/// <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.
[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文件.
以上是“WinForm中預覽Office文件的方法”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯行業(yè)資訊頻道!
分享標題:WinForm中預覽Office文件的方法-創(chuàng)新互聯
文章地址:http://chinadenli.net/article22/pspjc.html
成都網站建設公司_創(chuàng)新互聯,為您提供搜索引擎優(yōu)化、關鍵詞優(yōu)化、云服務器、企業(yè)建站、App開發(fā)、手機網站建設
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯