在 WPF 中查看 Word 文档
本文关键字:Word 文档 WPF | 更新日期: 2023-09-27 18:30:27
这是我的程序查看文件word文档,运行程序时从FileDialog中选择文件不显示任何内容,我添加了DocX作为参考,其中有什么错误?
<Window x:Class="Wordviewer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="524" Width="901">
<Grid Background="#FF464966">
<DocumentViewer HorizontalAlignment="Left" Margin="12,41,0,0"
Name="documentViewer1" VerticalAlignment="Top" Height="508" Width="923" BorderBrush="#FFA28D8D" />
<TextBox Height="29" HorizontalAlignment="Left" Margin="12,6,0,0"
Name="FileNameTextBox" VerticalAlignment="Top" Width="730" TextChanged="SelectedFileTextBox_TextChanged" />
<Button Content="Browse" Height="30" HorizontalAlignment="Left" Margin="757,6,0,0"
Name="BrowseButton" VerticalAlignment="Top" Width="178" Click="BrowseButton_Click" FontWeight="Bold">
<Button.BorderBrush>
<LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
<GradientStop Color="Black" Offset="0" />
<GradientStop Color="#FFD0BDBD" Offset="1" />
</LinearGradientBrush>
</Button.BorderBrush>
</Button>
</Grid>
而这个
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".doc";
dlg.Filter = "Word documents|*.doc;*.docx";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
FileNameTextBox.Text = filename;
var document = DocX.Load(filename);
string contents = document.Text;
// Use the file
}
}
简而言之,你不能。WPF 中的DocumentViewer
控件无法显示 Word 文档文件(.doc
、.docx
)。它旨在显示XPS文件,这是一种概念上类似于PDF的文档。
),因为它们是可编辑、可重排、结构化的文档,而 PDF 和 XPS 文档本质上只是告诉打印机要打印的内容(如 PostScript) - 将其视为将矢量绘图与光栅图像进行比较,即使它们看起来都相同。
有一些方法可以解决这个问题,它们都涉及将Word文档转换为XPS。第一种方法是使用办公自动化在进程中加载 Word 并将文档转换为 XPS,这要求在系统上安装 Word 并使其可用。第二种选择是使用第三方库,如 Aspose 或 Gem。
您实际上有一个选项,您可以使用 Office 互操作库,使用这些库打开 Word 文档,然后将它们另存为 XPS,然后您可以查看它。但我认为这有点沉重。
检查这个: http://www.dotnetperls.com/word