最近项目中遇到要嵌入WORD文档 ,网上查找了些资料,发现VS是提供这个控件的。
DocumentViewer控件可插入WORD EXCEL PDF TXT等等,很强大的一个东西。
我的需求是嵌入word的文档,显示数据以及保持时将数据以及数据的样式以二进制的形式存入数据库。这就涉及3步,1读取WORD文档 2将数据存入数据库 3下次打开的时候需要从数据库的数据显示在嵌入的word的文档中。
首先第一步使用DocumentViewer控件 我单独将这个控件拿出来了
后台代码
public string wordFilePath
{
set;
get;
}
private XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename)
{
// Create a WordApplication and host word document
Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
try
{
wordApp.Documents.Open(wordFilename);
// To Invisible the word document
wordApp.Application.Visible = false;
// Minimize the opened word document
wordApp.WindowState = WdWindowState.wdWindowStateMinimize;
Document doc = wordApp.ActiveDocument;
doc.SaveAs(xpsFilename, WdSaveFormat.wdFormatXPS);
XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read);
return xpsDocument;
}
catch (Exception ex)
{
MessageBox.Show("发生错误,该错误消息 " + ex.ToString());
return null;
}
finally
{
wordApp.Documents.Close();
((_Application)wordApp).Quit(WdSaveOptions.wdDoNotSaveChanges);
}
}
///
/// 将word转换为XPS文件
///
///
public void ConvertWordToXPS(string wordDocName)
{
string wordDocument = wordDocName;
if (string.IsNullOrEmpty(wordDocument) || !File.Exists(wordDocument))
{
MessageBox.Show("该文件是无效的。请选择一个现有的文件.");
}
else
{
string convertedXpsDoc = string.Concat(Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps");
XpsDocument xpsDocument = ConvertWordToXps(wordDocument, convertedXpsDoc);
if (xpsDocument == null)
{
return;
}
documentviewWord.Document = xpsDocument.GetFixedDocumentSequence();
}
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
if (wordFilePath != null)
{
try
{
ConvertWordToXPS(wordFilePath);
}
catch (Exception)//纯string文本
{
}
}
}
wordFilePath是word路径是由调用的该自定义控件的界面传入的。
这时候遇到一个问题,怎么把
XpsDocument 格式的数据转为二进制的呢 以及二进制如何转换为 XpsDocument格式呢,我找了半天也没解决。后来,想了个折中的办法,将word转为二进制存入数据库这个简单,然后下次读取的时候将二进制存到当前系统的临时文件夹下面,存为word,然后和上面一样读取word,这样就解决了,哈哈。如果有人知道
XpsDocument 和二进制之间的转换,欢迎指点。
这里讲word与二进制之间的转换贴出来
///
/// 文件转换为二进制
///
///
///
private byte[] wordConvertByte(string wordPath)
{
byte[] bytContent = null;
System.IO.FileStream fs = null;
System.IO.BinaryReader br = null;
try
{
fs = new FileStream(wordPath, System.IO.FileMode.Open);
}
catch
{
}
br = new BinaryReader((Stream)fs);
bytContent = br.ReadBytes((Int32)fs.Length);
return bytContent;
}
///
/// 将二进制保存为word
///
///
///
protected void ConvertWord(byte[] data, string filepath)
{
FileStream fs = new FileStream(filepath, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(data, 0, data.Length);
bw.Close();
fs.Close();
}