Spire.Doc組件讀取與寫入Word,spire.doc組件word
之前寫了一篇開源組件DocX讀寫word的文章,當時時間比較匆忙選了這個組件,使用過程中還是有些不便,不能提前定義好模版,插入Form表單域進行替換。最近無意中發現Spire.Doc組件功能很強大,目前來看基本上符合我的所有使用場景。本篇將挑選幾個重要的應用場景進行介紹。
閱讀目錄
回到頂部
使用模版生成簡歷
使用word的FormField預先插入占位符,然後在代碼中獲取所有FormField,進行替換。這種場景特別適用於,模版固定動態更改內容。看看最終效果

表單域制作步驟
1.打開word中的開發工具選項,對於導航欄中沒有這一項的,可以通過 文件->選項->自定義功能區->開發工具 進行打開

2.插入TextField, 屬性->設置書簽名稱


模版制作完成後,來看看實現代碼
class Program
{
private static BindingFlags s_flag = BindingFlags.Instance | BindingFlags.Public;
static void Main(string[] args)
{
Console.WriteLine("\nRunning Examples");
Resume personResume = new Resume
{
Name = "Spire.Doc",//姓名
Marriage = "未婚",//婚姻
Birth = "2010-09-19",//出生年月
Political = "團員",//政治面貌
Sex = "男",//性別
Nation = "漢族",//民族
Degree = "大學本科",//學位
Mobile = "13567890987",//移動電話
Professional = "軟件工程",//專業
Email = "[email protected]",//郵箱
Adress = "故宮", //地址
MajorCourse = "數據結構,C語言,算法,C++",//主修課程
PersonalAbility = "熟練掌握DocX操作Word,SQL能力強悍",//個人能力
ComputerAbility = "高級軟件工程師",//計算機能力
LanguageLevel = "CET-4,CET-6",//外語水平
Awards = "1999年幾月 曾獲優秀班干部,3等獎學金1999年幾月 曾獲校優秀干部,學生會先進集體,2等獎學金20**年幾月 曾獲優秀學習委員,網絡技術協會負責人,……………………",//獎勵情況
SelfEvaluation = "本人性格開朗、穩重、有活力,待人熱情、真誠;工作認真負責,積極主動,能吃苦耐勞,用於承受壓力,勇於創新;有很強的組織能力和團隊協作精神,具有較強的適應能力;紀律性強,工作積極配合;意志堅強,具有較強的無私奉獻精神"//自我評價
};
CreateResume(personResume);
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
private static void CreateResume(Resume personResume)
{
Document doc = new Document(@"ResumeTemplate.docx");
//清除表單域陰影
doc.Properties.FormFieldShading=false;
try
{
Type type = typeof(Resume);
PropertyInfo[] properties = type.GetProperties(s_flag);
int length = properties.Length;
Dictionary<string, PropertyInfo> dict = new Dictionary<string, PropertyInfo>(length, StringComparer.OrdinalIgnoreCase);
foreach (PropertyInfo prop in properties)
{
dict[prop.Name] = prop;
}
object value = null;
foreach (FormField field in doc.Sections[0].Body.FormFields)
{
//field.name對應設置模版文本域名稱
PropertyInfo prop = dict[field.Name];
if (prop != null)
{
value = prop.GetValue(personResume, null);
if (value != null && value != DBNull.Value)
{
switch (field.Type)
{
case FieldType.FieldFormTextInput:
field.Text = value.ToString();
break;
default:
break;
}
}
}
}
doc.SaveToFile(@"DocXResume.docx", FileFormat.Docx);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

![]()
public class Resume
{
public string Name { get; set; }
public string Marriage { get; set; }
public string Birth { get; set; }
public string Political { get; set; }
public string Sex { get; set; }
public string Nation { get; set; }
public string Degree { get; set; }
public string Mobile { get; set; }
public string Professional { get; set; }
public string Email { get; set; }
public string Adress { get; set; }
public string MajorCourse { get; set; }
public string PersonalAbility { get; set; }
public string ComputerAbility { get; set; }
public string LanguageLevel { get; set; }
public string Awards { get; set; }
public string SelfEvaluation { get; set; }
}
View Code
重點關注上面標紅的代碼,可以看到通過簡單的代碼即可完成一份簡歷文檔
回到頂部
格式轉換
使用Spire.Doc可以很方便的將word轉換成HTML,RTF,PDF,TXT,WPS...等格式
Document doc = new Document(@"SpireDocResume.docx"); //Save doc file.
doc.SaveToFile("SpireDocResume.html", FileFormat.Html);

效果和直接打開word是一樣的,有了這功能就能實現在線word預覽,之前的一篇在線文檔預覽方案也可以參考一下。其它格式的轉換也是一樣的代碼,改一下FileFormat枚舉值即可。
回到頂部
Table操作

private static void addTable(Section section)
{
String[] header = { "Name", "Capital", "Continent", "Area", "Population" };
String[][] data =
{
new String[]{"Argentina", "Buenos Aires", "South America", "2777815", "32300003"},
new String[]{"Bolivia", "La Paz", "South America", "1098575", "7300000"},
new String[]{"Brazil", "Brasilia", "South America", "8511196", "150400000"},
new String[]{"Canada", "Ottawa", "North America", "9976147", "26500000"},
new String[]{"Chile", "Santiago", "South America", "756943", "13200000"},
new String[]{"Colombia", "Bagota", "South America", "1138907", "33000000"},
new String[]{"Cuba", "Havana", "North America", "114524", "10600000"},
new String[]{"Ecuador", "Quito", "South America", "455502", "10600000"},
new String[]{"El Salvador", "San Salvador", "North America", "20865", "5300000"},
new String[]{"Guyana", "Georgetown", "South America", "214969", "800000"},
new String[]{"Jamaica", "Kingston", "North America", "11424", "2500000"},
new String[]{"Mexico", "Mexico City", "North America", "1967180", "88600000"},
new String[]{"Nicaragua", "Managua", "North America", "139000", "3900000"},
new String[]{"Paraguay", "Asuncion", "South America", "406576", "4660000"},
new String[]{"Peru", "Lima", "South America", "1285215", "21600000"},
new String[]{"United States of America", "Washington", "North America", "9363130", "249200000"},
new String[]{"Uruguay", "Montevideo", "South America", "176140", "3002000"},
new String[]{"Venezuela", "Caracas", "South America", "912047", "19700000"}
};
Spire.Doc.Table table = section.AddTable();
table.ResetCells(data.Length + 1, header.Length);
// ***************** First Row *************************
TableRow row = table.Rows[0];
row.IsHeader = true;
row.Height = 20; //unit: point, 1point = 0.3528 mm
row.HeightType = TableRowHeightType.Exactly;
row.RowFormat.BackColor = Color.Gray;
for (int i = 0; i < header.Length; i++)
{
row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph p = row.Cells[i].AddParagraph();
p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
TextRange txtRange = p.AppendText(header[i]);
txtRange.CharacterFormat.Bold = true;
}
for (int r = 0; r < data.Length; r++)
{
TableRow dataRow = table.Rows[r + 1];
dataRow.Height = 20;
dataRow.HeightType = TableRowHeightType.Exactly;
dataRow.RowFormat.BackColor = Color.Empty;
for (int c = 0; c < data[r].Length; c++)
{
dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
dataRow.Cells[c].AddParagraph().AppendText(data[r][c]);
}
}
}
View Code
回到頂部
總結
通過上面三個簡單的例子,粗略的了解了Spire.Doc。下面就我個人對DocX和Spire.Doc使用,列出兩種優缺點。
Spire.Doc
DocX
API
介紹簡單
無API介紹
Demo
提供了很多Demo方便學習
demo少
收費
收費
開源免費
功能對比
1.支持FormField模版替換 2.Table讀寫功能強大
1.對自定義屬性讀寫存在BUG
兼容性
兼容word各版本
支持2007即以上版本
依賴性
不依賴於office,即使服務器未裝office也能正常操作
實際開發中可以根據自己需要來選擇使用Sprie.Doc或者DocX。
本文例子Demo下載地址:SpireDoc_Demo
如果,您認為閱讀這篇博客讓您有些收獲,不妨點擊一下右下角的【推薦】按鈕。
如果,您希望更容易地發現我的新博客,不妨點擊一下綠色通道的【關注我】。
因為,我的寫作熱情也離不開您的肯定支持。
感謝您的閱讀,如果您對我的博客所講述的內容有興趣,請繼續關注我的後續博客,我是焰尾迭 。