在C#中使用Spire.doc對word的操作總結
在最近的工程中我們要處理一些word文檔。通過在網上的大量搜索,我發現大多數軟件功能不是不完整就是有重復。極少數可以完全實現的word組件又要收費。功夫不負有心人,終於找到了可以滿足我們需要的免費的C# word程序庫。為了和其他的作比較,我在這里先做以下匯總。希望對大家有幫助。
如何得到?
這個免費版的word 組件可以在Codeplex下載到,你也可以從本文里直接下載msi文件。它還提供了一些源代碼。
Word操作匯總
1、 打開已有word文件,這是要處理word文件的最基本也是必須的步驟。他提供了三種方法。
方法1:從已知特定的文檔中初始化一個新的Document 類的實例
Document document = new Document(@"..\..\Sample.docx");
方法2、從文件中加載一個word文件
Document document =
new Document();
document.LoadFromFile( @" ..\..\Sample.docx ");
document.LoadFromFile( @" ..\..\Sample.docx ");
方法3、從流文件中加載word文件
Stream stream = File.OpenRead(
@"
..\..\Sample.docx
");
Document document = new Document(stream);
Document document = new Document(stream);
2、如何創建表格
Document document =
new Document();
Section section = document.AddSection();
Table table = section.AddTable( true);
table.ResetCells( 2, 3);
TableRow row = table.Rows[ 0];
row.IsHeader = true;
Paragraph para = row.Cells[ 0].AddParagraph();
TextRange TR = para.AppendText( " Item ");
para = row.Cells[ 1].AddParagraph();
TR = para.AppendText( " Description ");
para = row.Cells[ 2].AddParagraph();
TR = para.AppendText( " Qty ");
document.SaveToFile( " WordTable.docx ");
System.Diagnostics.Process.Start( " WordTable.docx ");
Section section = document.AddSection();
Table table = section.AddTable( true);
table.ResetCells( 2, 3);
TableRow row = table.Rows[ 0];
row.IsHeader = true;
Paragraph para = row.Cells[ 0].AddParagraph();
TextRange TR = para.AppendText( " Item ");
para = row.Cells[ 1].AddParagraph();
TR = para.AppendText( " Description ");
para = row.Cells[ 2].AddParagraph();
TR = para.AppendText( " Qty ");
document.SaveToFile( " WordTable.docx ");
System.Diagnostics.Process.Start( " WordTable.docx ");

我們還可以設置行高和列寬
3、如何插入超鏈接?你可以插入兩種超鏈接,Email 鏈接和webmail 鏈接。
Documentdocument =newDocument();
Section section = document.AddSection();
// Insert URL hyperlink
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText( " Home page ");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink( " www.e-iceblue.com ", " www.e-iceblue.com ",HyperlinkType.WebLink);
// Insert email address hyperlink
paragraph = section.AddParagraph();
paragraph.AppendText( " Contact US ");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink( " mailto:support@e-iceblue.com ", " support@e-iceblue.com ",HyperlinkType.EMailLink);
document.SaveToFile( " Hyperlink.docx ");
System.Diagnostics.Process.Start( " Hyperlink.docx ");
Section section = document.AddSection();
// Insert URL hyperlink
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText( " Home page ");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink( " www.e-iceblue.com ", " www.e-iceblue.com ",HyperlinkType.WebLink);
// Insert email address hyperlink
paragraph = section.AddParagraph();
paragraph.AppendText( " Contact US ");
paragraph.ApplyStyle(BuiltinStyle.Heading2);
paragraph = section.AddParagraph();
paragraph.AppendHyperlink( " mailto:support@e-iceblue.com ", " support@e-iceblue.com ",HyperlinkType.EMailLink);
document.SaveToFile( " Hyperlink.docx ");
System.Diagnostics.Process.Start( " Hyperlink.docx ");

4、如何加入注解
Document document =
new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText( " Home Page of ");
TextRange textRange = paragraph.AppendText( " e-iceblue ");
Comment comment1 = paragraph.AppendComment( " www.e-iceblue.com ");
comment1.AddItem(textRange);
comment1.Format.Author = " Harry Hu ";
comment1.Format.Initial = " HH ";
document.SaveToFile( " Comment.docx ");
System.Diagnostics.Process.Start( " Comment.docx ");
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AppendText( " Home Page of ");
TextRange textRange = paragraph.AppendText( " e-iceblue ");
Comment comment1 = paragraph.AppendComment( " www.e-iceblue.com ");
comment1.AddItem(textRange);
comment1.Format.Author = " Harry Hu ";
comment1.Format.Initial = " HH ";
document.SaveToFile( " Comment.docx ");
System.Diagnostics.Process.Start( " Comment.docx ");

5、如何加入書簽
Document document =
new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart( " SimpleBookMark ");
paragraph.AppendText( " This is a simple book mark. ");
paragraph.AppendBookmarkEnd( " SimpleBookMark ");
document.SaveToFile( " Bookmark.docx ");
System.Diagnostics.Process.Start( " Bookmark.docx ");
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart( " SimpleBookMark ");
paragraph.AppendText( " This is a simple book mark. ");
paragraph.AppendBookmarkEnd( " SimpleBookMark ");
document.SaveToFile( " Bookmark.docx ");
System.Diagnostics.Process.Start( " Bookmark.docx ");

6、合並郵件
Document document =
new Document();
document.LoadFromFile( " Fax.doc ");
string[] filedNames = new string[] { " Contact Name ", " Fax ", " Date " };
string[] filedValues = new string[] { " John Smith ", " +1 (69) 123456 ", System.DateTime.Now.Date.ToString() };
document.MailMerge.Execute(filedNames, filedValues);
document.SaveToFile( " MailMerge.doc ", FileFormat.Doc);
System.Diagnostics.Process.Start( " MailMerge.doc ");
document.LoadFromFile( " Fax.doc ");
string[] filedNames = new string[] { " Contact Name ", " Fax ", " Date " };
string[] filedValues = new string[] { " John Smith ", " +1 (69) 123456 ", System.DateTime.Now.Date.ToString() };
document.MailMerge.Execute(filedNames, filedValues);
document.SaveToFile( " MailMerge.doc ", FileFormat.Doc);
System.Diagnostics.Process.Start( " MailMerge.doc ");

7、加入表單,這部分包含創建以及填入表單域。
創建表單
//
Add new section to document
Section section = document.AddSection();
// Add Form to section
private void AddForm(Section section)
// add text input field
TextFormField field
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;
// add dropdown field
DropDownFormField list
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;
// add checkbox field
fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);
Section section = document.AddSection();
// Add Form to section
private void AddForm(Section section)
// add text input field
TextFormField field
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField;
// add dropdown field
DropDownFormField list
= fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField;
// add checkbox field
fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox);

填入表單域
//
Fill data from XML file
using (Stream stream = File.OpenRead( @" ..\..\..\Data\User.xml "))
{
XPathDocument xpathDoc = new XPathDocument(stream);
XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode( " /user ");
Fill data:
foreach (FormField field in document.Sections[ 0].Body.FormFields)
{
String path = String.Format( " {0}/text() ", field.Name);
XPathNavigator propertyNode = user.SelectSingleNode(path);
if (propertyNode != null)
{
switch (field.Type)
{
case FieldType.FieldFormTextInput:
field.Text = propertyNode.Value;
break;
case FieldType.FieldFormDropDown:
DropDownFormField combox = field as DropDownFormField;
for( int i = 0; i < combox.DropDownItems.Count; i++)
{
if (combox.DropDownItems[i].Text == propertyNode.Value)
{
combox.DropDownSelectedIndex = i;
break;
}
if (field.Name == " country " && combox.DropDownItems[i].Text == " Others ")
{
combox.DropDownSelectedIndex = i;
}
}
break;
case FieldType.FieldFormCheckBox:
if (Convert.ToBoolean(propertyNode.Value))
{
CheckBoxFormField checkBox = field as CheckBoxFormField;
checkBox.Checked = true;
}
break;
}
}
}
}
using (Stream stream = File.OpenRead( @" ..\..\..\Data\User.xml "))
{
XPathDocument xpathDoc = new XPathDocument(stream);
XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode( " /user ");
Fill data:
foreach (FormField field in document.Sections[ 0].Body.FormFields)
{
String path = String.Format( " {0}/text() ", field.Name);
XPathNavigator propertyNode = user.SelectSingleNode(path);
if (propertyNode != null)
{
switch (field.Type)
{
case FieldType.FieldFormTextInput:
field.Text = propertyNode.Value;
break;
case FieldType.FieldFormDropDown:
DropDownFormField combox = field as DropDownFormField;
for( int i = 0; i < combox.DropDownItems.Count; i++)
{
if (combox.DropDownItems[i].Text == propertyNode.Value)
{
combox.DropDownSelectedIndex = i;
break;
}
if (field.Name == " country " && combox.DropDownItems[i].Text == " Others ")
{
combox.DropDownSelectedIndex = i;
}
}
break;
case FieldType.FieldFormCheckBox:
if (Convert.ToBoolean(propertyNode.Value))
{
CheckBoxFormField checkBox = field as CheckBoxFormField;
checkBox.Checked = true;
}
break;
}
}
}
}

8、合並word文檔
//
Load two documents
// Load Document1 and Document2
Document DocOne = new Document();
DocOne.LoadFromFile( @" E:\Work\Document\welcome.docx ", FileFormat.Docx);
Document DocTwo = new Document();
DocTwo.LoadFromFile( @" E:\Work\Document\New Zealand.docx ", FileFormat.Docx);
// Merge
foreach (Section sec in DocTwo.Sections)
{
DocOne.Sections.Add(sec.Clone());
}
// Save and Launch
DocOne.SaveToFile( " Merge.docx ", FileFormat.Docx);
// Load Document1 and Document2
Document DocOne = new Document();
DocOne.LoadFromFile( @" E:\Work\Document\welcome.docx ", FileFormat.Docx);
Document DocTwo = new Document();
DocTwo.LoadFromFile( @" E:\Work\Document\New Zealand.docx ", FileFormat.Docx);
// Merge
foreach (Section sec in DocTwo.Sections)
{
DocOne.Sections.Add(sec.Clone());
}
// Save and Launch
DocOne.SaveToFile( " Merge.docx ", FileFormat.Docx);
9、保護文檔。你可以設置密碼或者加入水印來進行保護。文字和圖片的水印都支持。
//
Protect with password
document.Encrypt( " eiceblue ");
// Add Text watermark:
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = " Microsoft ";
txtWatermark.FontSize = 90;
txtWatermark.Layout = WatermarkLayout.Diagonal;
document.Watermark = txtWatermark;
// Add Image watermark:
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile( @" ..\imagess.jpeg ");
picture.Scaling = 250;
document.Watermark = picture;
document.Encrypt( " eiceblue ");
// Add Text watermark:
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = " Microsoft ";
txtWatermark.FontSize = 90;
txtWatermark.Layout = WatermarkLayout.Diagonal;
document.Watermark = txtWatermark;
// Add Image watermark:
PictureWatermark picture = new PictureWatermark();
picture.Picture = System.Drawing.Image.FromFile( @" ..\imagess.jpeg ");
picture.Scaling = 250;
document.Watermark = picture;
10、轉換功能是在處理word文檔時最常見的操作了。使用免費版的Spire.doc for .NET, 轉換變得很簡單。只要包含三行類似的代碼你就可以把word轉換成其他常用格式,像PDF,HTML和圖片。
Word轉換成PDF
SaveToFile(
"
Target PDF.PDF
", FileFormat.PDF);
Word轉換成圖片
Image image = document.SaveToImages(
0, ImageType.Bitmap);
image.Save( " Sample.tiff ", ImageFormat.Tiff);
image.Save( " Sample.tiff ", ImageFormat.Tiff);
Word轉換成HTML
document.SaveToFile(
"
Target HTML.html
", FileFormat.Html);
WordDocViewer( ""Target HTML.html " );
WordDocViewer( ""Target HTML.html " );
結論:
這是一個免費又強大的C# word 組件,它不需要 Word automatio即可運行,並且任何第三方的功能都囊括。
