aspose.word使用簡單方法


概念介紹

使用aspose生成word報表步驟:

  1. 加載word模板
  2. 提供數據源
  3. 填充

加載模板

提供了4種重載方法

  public Document();
  public Document(Stream stream);
  public Document(string fileName);
  public Document(Stream stream, LoadOptions loadOptions);
  public Document(string fileName, LoadOptions loadOptions);

模板制作

aspose在word模板中使用了域(MergeField),一個域相當於一個占位符。域,可以從菜單  插入->文檔部件中定位選擇。

數據填充

目前有兩種情況:基本信息和列表。

基本信息:基本屬性,列表對應循環的數據結構,如DataTable.

對於列表,使用DataTable進行填充。

模板的制作:

表格以關鍵字TableStart開頭,TableEnd結束。關鍵字后加DataTable表名稱。e.g.TableStart:tableName

表頭中間,是具體字段的名稱。

 序號 姓名 性別 年齡
 <TableStart:Name><<Index>>  <<Name>>  <<Sex>> <<Age>><<TableEnd:Name>>
Document doc = new Document(Server.MapPath("~\\templet") + "\\" + name);
doc.MailMerge.ExecuteWithRegions(DataTable)

 具體字段

有兩種方式可以實現:

方法一、

DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField(MergeFiled Name);
builder.Write(value;

這種方式,一次填充一個數據。但一個域字段可以多次使用,並可以一次填充。

優點,可以靈活定制。如果要想一次替換多個域字段,稍加改動同樣可以實現。

DocumentBuilder builder = new DocumentBuilder(doc);
while(builder.MoveToMergeField(MergeFiled Name))
{
    builder.Write(value;
}

方法二、

 doc.MailMerge.Execute(fieldNames, fieldValues);

在具體開發過程中,通常選擇Entity作為數據源。可通過反射獲取數據。

如何獲取域字段

doc.MailMerge.GetFieldNames()

方法返回的書string[]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM