有時我們希望在C#程序中能夠直接操作word,實現向word中寫入數據打印或呈交給相關人員,下面就以一個例子講解了具體的操作方法。
本例演示了打開word文檔、在word文檔中創建表格,合并單元格,保存word文檔并退出等功能。
using System;
using System.Web;
using Microsoft.Office.Interop.Word;
namespace CustomFileAccess
{
public class WordOperator
{
public void CreateWord()
{
Microsoft.Office.Interop.Word.Application wordApp = new Application();
Microsoft.Office.Interop.Word.Document wordDocument = new Document();
Microsoft.Office.Interop.Word.Table wordTable;
Microsoft.Office.Interop.Word.Table wordTableCopy;
object myNull = System.Reflection.Missing.Value;
object strPath = HttpContext.Current.Server.MapPath(@"WordTemplete/MyWordTemplete.doc");
object styleName = "Table Grid 8";
try
{
wordDocument = wordApp.Documents.Open(ref strPath, ref myNull, ref myNull, ref myNull,
ref myNull, ref myNull, ref myNull, ref myNull, ref myNull, ref myNull, ref myNull, ref myNull,
ref myNull, ref myNull, ref myNull, ref myNull);
object start = 0;
object end = 0;
Microsoft.Office.Interop.Word.Range wordRange = wordDocument.Range(ref start, ref end);
wordTable = wordDocument.Tables.Add(wordRange, 3, 13, ref myNull, ref myNull);
wordTable.Borders.OutsideColor = WdColor.wdColorAutomatic;
wordTable.Borders.OutsideColorIndex = WdColorIndex.wdAuto;
wordTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
wordTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;
wordTable.Borders.InsideColor = WdColor.wdColorAutomatic;
wordTable.Borders.InsideColorIndex = WdColorIndex.wdAuto;
wordTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
wordTable.Borders.InsideLineWidth = WdLineWidth.wdLineWidth050pt;
wordDocument.Tables[1].Cell(1, 1).Merge(wordDocument.Tables[1].Cell(2, 1));
wordDocument.Tables[1].Cell(1, 1).Range.Text = "cell 1, 1";
wordDocument.Tables[1].Cell(2, 2).Range.Text = "cell 2, 2";
wordDocument.Tables[1].Select();
wordApp.Selection.Copy();
wordDocument.Tables[1].Cell(1, 2).Range.Text = "The First Table";
object myunit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
wordApp.Selection.EndKey(ref myunit, ref myNull);
wordApp.Selection.TypeParagraph();
wordApp.Selection.Paste();
wordDocument.Tables[2].Cell(1, 1).Range.Text = "The Second Table";
wordDocument.Save();
}
catch
{
wordDocument.Close(ref myNull, ref myNull, ref myNull);
wordApp.Quit(ref myNull, ref myNull, ref myNull);
if (wordDocument != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocument);
wordDocument = null;
}
if (wordApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
wordApp = null;
}
GC.Collect();
throw new Exception("文檔生成失敗!");
}
finally
{
wordDocument.Close(ref myNull, ref myNull, ref myNull);
wordApp.Quit(ref myNull, ref myNull, ref myNull);
}
}
}
}
|
新聞熱點
疑難解答
圖片精選