WinForm預覽Office文檔 使用WinForm, WPF, Office組件 原理:使用Office COM組件將Word,Excel轉換為XPS文檔, 將WPF的 控制項寄宿到WinForm中, 實現預覽. 1. 新建WinForm項目 2. 新建WPF用戶控制項, 註意是WPF控制項 3. 編 ...
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文件.