最近項目中遇到要嵌入WORD文檔 ,網上查找了些資料,發現VS是提供這個控件的。
DocumentViewer控件可插入WORD EXCEL PDF TXT等等,很強大的一個東西。
我的需求是嵌入word的文檔,顯示數據以及保持時將數據以及數據的樣式以二進制的形式存入數據庫。這就涉及3步,1讀取WORD文檔 2將數據存入數據庫 3下次打開的時候需要從數據庫的數據顯示在嵌入的word的文檔中。
首先第一步使用DocumentViewer控件 我單獨將這個控件拿出來了
<Grid>
<DocumentViewer Grid.Row="1" Name="documentviewWord" VerticalAlignment="Top" HorizontalAlignment="Left"/>
</Grid>
后台代碼
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);
}
}
/// <summary>
/// 將word轉換為XPS文件
/// </summary>
/// <param name="wordDocName"></param>
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與二進制之間的轉換貼出來
/// <summary>
/// 文件轉換為二進制
/// </summary>
/// <param name="wordPath"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 將二進制保存為word
/// </summary>
/// <param name="data"></param>
/// <param name="filepath"></param>
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();
}
