Aspose.Words是一款優秀的工具,能在不依賴Microsoft.Office環境的條件下實現對Word文檔的處理和生成。通過Aspose.Words提供的相關API,能在Word中根據需要創建各種各樣的表格。
表格的展現形式往往是由所要展現的數據結構形式所展現的,不同的數據結構就需要不同的表格來呈現,所以首先要清楚自己有什麼樣的數據結構或什麼樣的展現形式,這樣就能理清思路通過Aspose.Words提供的一系列API進行自由創作了。
1.創建普通表格
1.1表格效果
1.2數據結構
典型的列表結構
public class GoodsModel
{
/// <summary>
/// 貨品名稱
/// </summary>
public string GoodsName { get; set; }
/// <summary>
/// 貨品類型
/// </summary>
public string GoodsType { get; set; }
/// <summary>
/// 存放位置
/// </summary>
public string Location { get; set; }
/// <summary>
/// 貨品數量
/// </summary>
public int GoodsNum { get; set; }
}
1.3實現代碼
public static void BuildFile(string savePath)
{
Document doc = new Document();//文檔實例
DocumentBuilder builder = new DocumentBuilder(doc);//文檔構造器
List<GoodsModel> list = MakeListData();//生成測試數據
CreateSimpleTable(doc, builder, list);//創建表格
doc.Save(savePath);
}
private static void CreateSimpleTable(Document doc,DocumentBuilder builder,List<GoodsModel> list)
{
Table table = builder.StartTable();
#region 表頭
string[] titles = new string[] { "序號", "貨品名稱", "貨品類型", "存放位置", "數量" };
int[] lens = new int[] { 10, 25, 25, 25, 15 };
for (int i=0;i<5;i++)
{
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[i]);//列寬-百分比
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGray;//背景色-灰色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write(titles[i]);//寫入內容
}
builder.EndRow();//結束行
#endregion
#region 內容
for (int i=0;i<list.Count;i++)
{
GoodsModel model = list[i];
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[0]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write((i + 1).ToString());//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[1]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//對齊-靠左
builder.Write(model.GoodsName);//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[2]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write(model.GoodsType);//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[3]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;//對齊-靠右
builder.Write(model.Location);//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[4]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write((model.GoodsNum).ToString());//寫入內容
builder.EndRow();//結束行
}
#endregion
builder.EndTable();//結束表格
}
private static List<GoodsModel> MakeListData()
{
List<GoodsModel> list = new List<GoodsModel>();
GoodsModel model1 = new GoodsModel { GoodsName = "礦泉水", GoodsType = "酒水飲料", Location = "1號庫", GoodsNum = 100 };
GoodsModel model2 = new GoodsModel { GoodsName = "純淨水", GoodsType = "酒水飲料", Location = "1號庫", GoodsNum = 400 };
GoodsModel model3 = new GoodsModel { GoodsName = "蘇打水", GoodsType = "酒水飲料", Location = "1號庫", GoodsNum = 200 };
GoodsModel model4 = new GoodsModel { GoodsName = "啤酒", GoodsType = "酒水飲料", Location = "1號庫", GoodsNum = 100 };
list.Add(model1);
list.Add(model2);
list.Add(model3);
list.Add(model4);
return list;
}
注意:Aspose.Words提供了DataTable直接生成表格的方法。
2.創建多級表格
2.1表格效果
2.2數據結構
類似樹狀的多級嵌套結構。
public class Classify
{
/// <summary>
/// 分類名稱
/// </summary>
public string ClassifyName { get; set; }
/// <summary>
/// 分類級別
/// </summary>
public int ClassfyLevel { get; set; }
/// <summary>
/// 分類編碼
/// </summary>
public string ClassifyCode { get; set; }
/// <summary>
/// 父級分類
/// </summary>
public Classify Parent { get; set; }
/// <summary>
/// 子級分類
/// </summary>
public List<Classify> Children { get; set; }
}
2.3實現代碼
public static void BuildFile(string savePath)
{
Document doc = new Document();//文檔實例
DocumentBuilder builder = new DocumentBuilder(doc);//文檔構造器
List<Classify> tree = MakeTreeData();//生成測試數據
CreateTreeTable(doc, builder, tree);/創建表格
doc.Save(savePath);//保存文檔
}
private static void CreateTreeTable(Document doc,DocumentBuilder builder,List<Classify> tree)
{
Table table = builder.StartTable();
#region 表頭
string[] titles = new string[] { "序號", "大類名稱", "大類編碼", "小類名稱", "小類編碼", "細類名稱", "細類編碼" };
int[] lens = new int[] { 4, 16, 16, 16, 16, 16, 16 };
for (int i = 0; i < 7; i++)
{
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[i]);//列寬-百分比
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGray;//背景色-灰色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write(titles[i]);//寫入內容
}
builder.EndRow();//結束行
#endregion
int index = 1;//序號
for (int i=0;i<tree.Count; i++)//大類
{
Classify node1 = tree[i];
int num1 = 0;
for (int j=0;j<node1.Children.Count;j++)//小類
{
Classify node2 = node1.Children[j];
int num2 = 0;
for (int k=0;k<node2.Children.Count;k++)//細類
{
Classify node3 = node2.Children[k];
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[0]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊
builder.Write(index.ToString());//寫入內容
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[1]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊
if (num1 == 0)
{
builder.Write(node1.ClassifyName);//寫入內容
builder.CellFormat.VerticalMerge = CellMerge.First;
}
else//合併單元格
{
builder.CellFormat.VerticalMerge = CellMerge.Previous;
}
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[2]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊
if (num1 == 0)
{
builder.Write(node1.ClassifyCode);//寫入內容
builder.CellFormat.VerticalMerge = CellMerge.First;
}
else//合併單元格
{
builder.CellFormat.VerticalMerge = CellMerge.Previous;
}
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[3]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊
if (num2 == 0)
{
builder.Write(node2.ClassifyName);//寫入內容
builder.CellFormat.VerticalMerge = CellMerge.First;
}
else//合併單元格
{
builder.CellFormat.VerticalMerge = CellMerge.Previous;
}
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[4]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊
if (num2 == 0)
{
builder.Write(node2.ClassifyCode);//寫入內容
builder.CellFormat.VerticalMerge = CellMerge.First;
}
else//合併單元格
{
builder.CellFormat.VerticalMerge = CellMerge.Previous;
}
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[5]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write(node3.ClassifyName);//寫入內容
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[6]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write(node3.ClassifyCode);//寫入內容
builder.EndRow();
index++;
num1++;
num2++;
}
}
}
#region 內容
#endregion
builder.EndTable();
}
private static List<Classify> MakeTreeData()
{
List<Classify> tree = new List<Classify>();
Classify node_1 = new Classify { ClassifyName = "酒水飲料", ClassifyCode = "01", ClassfyLevel = 1 };
Classify node_1_1 = new Classify { ClassifyName = "白酒", ClassifyCode = "0101", ClassfyLevel = 2 };
Classify node_1_2 = new Classify { ClassifyName = "紅酒", ClassifyCode = "0102", ClassfyLevel = 2 };
Classify node_1_3 = new Classify { ClassifyName = "啤酒", ClassifyCode = "0103", ClassfyLevel = 2 };
Classify node_1_1_1 = new Classify { ClassifyName = "茅臺", ClassifyCode = "010101", ClassfyLevel = 3 };
Classify node_1_1_2 = new Classify { ClassifyName = "五糧液", ClassifyCode = "010102", ClassfyLevel = 3 };
Classify node_1_2_1 = new Classify { ClassifyName = "法國", ClassifyCode = "010201", ClassfyLevel = 3 };
Classify node_1_2_2 = new Classify { ClassifyName = "澳大利亞", ClassifyCode = "010202", ClassfyLevel = 3 };
Classify node_1_3_1 = new Classify { ClassifyName = "黑啤", ClassifyCode = "010301", ClassfyLevel = 3 };
Classify node_1_3_2 = new Classify { ClassifyName = "黃啤", ClassifyCode = "010302", ClassfyLevel = 3 };
node_1_1.Children = new List<Classify> { node_1_1_1, node_1_1_2 };
node_1_2.Children = new List<Classify> { node_1_2_1, node_1_2_2 };
node_1_3.Children = new List<Classify> { node_1_3_1, node_1_3_2 };
node_1.Children = new List<Classify> { node_1_1, node_1_2, node_1_3 };
tree.Add(node_1);
Classify node_2 = new Classify { ClassifyName = "食品生鮮", ClassifyCode = "02", ClassfyLevel = 1 };
Classify node_2_1 = new Classify { ClassifyName = "新鮮水果", ClassifyCode = "0201", ClassfyLevel = 2 };
Classify node_2_2 = new Classify { ClassifyName = "蔬菜蛋品", ClassifyCode = "0202", ClassfyLevel = 2 };
Classify node_2_3 = new Classify { ClassifyName = "海鮮水產", ClassifyCode = "0203", ClassfyLevel = 2 };
Classify node_2_1_1 = new Classify { ClassifyName = "蘋果", ClassifyCode = "020101", ClassfyLevel = 3 };
Classify node_2_1_2 = new Classify { ClassifyName = "菠蘿", ClassifyCode = "020102", ClassfyLevel = 3 };
Classify node_2_2_1 = new Classify { ClassifyName = "西紅柿", ClassifyCode = "020201", ClassfyLevel = 3 };
Classify node_2_2_2 = new Classify { ClassifyName = "包菜", ClassifyCode = "020202", ClassfyLevel = 3 };
Classify node_2_3_1 = new Classify { ClassifyName = "蝦", ClassifyCode = "020301", ClassfyLevel = 3 };
Classify node_2_3_2 = new Classify { ClassifyName = "蟹", ClassifyCode = "020302", ClassfyLevel = 3 };
node_2_1.Children = new List<Classify> { node_2_1_1, node_2_1_2 };
node_2_2.Children = new List<Classify> { node_2_2_1, node_2_2_2 };
node_2_3.Children = new List<Classify> { node_2_3_1, node_2_3_2 };
node_2.Children = new List<Classify> { node_2_1, node_2_2, node_2_3 };
tree.Add(node_2);
return tree;
}
3.創建複雜表格
3.1表格效果
3.2數據結構
包含父子關係的單一嵌套結構
public class DbTable
{
/// <summary>
/// 表名
/// </summary>
public string TableName { get; set; }
/// <summary>
/// 英文名
/// </summary>
public string EnglishName { get; set; }
/// <summary>
/// 描述
/// </summary>
public string TableDescribe { get; set; }
/// <summary>
/// 列
/// </summary>
public List<DbColumn> Columns { get; set; }
}
public class DbColumn
{
/// <summary>
/// 列名
/// </summary>
public string ColumnName { get; set; }
/// <summary>
/// 英文名
/// </summary>
public string EnglishName { get; set; }
/// <summary>
/// 數據類型
/// </summary>
public string ColumnType { get; set; }
/// <summary>
/// 長度
/// </summary>
public int ColumnLength { get; set; }
/// <summary>
/// 描述
/// </summary>
public string ColumnDescribe { get; set; }
}
3.3實現代碼
public static void BuildFile(string savePath)
{
Document doc = new Document();//文檔示例
DocumentBuilder builder = new DocumentBuilder(doc);//文檔構造器
DbTable custom = MakeCustomData();//生成測試數據
CreateCustomTable(doc, builder, custom);//創建表格
doc.Save(savePath);//保存文檔
}
private static void CreateCustomTable(Document doc,DocumentBuilder builder,DbTable custom)
{
Table table = builder.StartTable();
#region 數據表信息
string[] titles = new string[] { "表名稱", "英文名稱", "描述" };
string[] values = new string[] { custom.TableName, custom.EnglishName, custom.TableDescribe };
int[] lens = new int[] { 6, 25, 25, 12, 14, 18 };
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 6; j++)
{
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[j]);
builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGray;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
if (j == 0)
{
builder.Write(titles[i]);
builder.CellFormat.HorizontalMerge = CellMerge.First;
}
else if (j >0&&j<3)
{
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
}
else if (j == 3)
{
builder.Write(values[i]);
builder.CellFormat.HorizontalMerge = CellMerge.First;
}
else
{
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
}
}
builder.EndRow();
}
#endregion
#region 數據列表頭
string[] colTiltes = new string[] { "序號", "列名", "英文名", "數據類型", "長度", "描述" };
for (int i = 0; i < 6; i++)
{
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[i]);//列寬-百分比
builder.CellFormat.Shading.BackgroundPatternColor = Color.Gray;//背景色-灰色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write(colTiltes[i]);//寫入內容
}
builder.EndRow();//結束行
#endregion
#region 數據列內容
for (int i = 0; i < custom.Columns.Count; i++)
{
DbColumn model = custom.Columns[i];
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[0]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write((i + 1).ToString());//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[1]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//對齊-靠左
builder.Write(model.ColumnName);//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[2]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write(model.EnglishName);//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[3]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;//對齊-靠右
builder.Write(model.ColumnType);//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[4]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write((model.ColumnLength).ToString());//寫入內容
builder.InsertCell();//插入單元格
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(lens[4]);//列寬
builder.CellFormat.Shading.BackgroundPatternColor = Color.White;//背景色-白色
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//對齊-居中
builder.Write(model.ColumnDescribe);//寫入內容
builder.EndRow();//結束行
}
#endregion
builder.EndTable();
}
private static DbTable MakeCustomData()
{
DbTable table = new DbTable { TableName = "貨品信息表", EnglishName = "GoodsInfo", TableDescribe = "描述貨品基本信息" };
DbColumn column1 = new DbColumn { ColumnName = "貨品名稱", EnglishName = "GoodsName", ColumnType = "文本", ColumnLength = 50, ColumnDescribe = "" };
DbColumn column2 = new DbColumn { ColumnName = "貨品類型", EnglishName = "GoodsType", ColumnType = "文本", ColumnLength = 50, ColumnDescribe = "貨品分類名稱" };
DbColumn column3 = new DbColumn { ColumnName = "存放位置", EnglishName = "Location", ColumnType = "文本", ColumnLength = 50, ColumnDescribe = "" };
DbColumn column4 = new DbColumn { ColumnName = "貨品數量", EnglishName = "GoodsNum", ColumnType = "整型", ColumnLength = 10, ColumnDescribe = "" };
table.Columns = new List<DbColumn> { column1, column2, column3, column4 };
return table;
}
4.根據標籤插入多個表格
一個Word文檔中往往並不只包含一個表格,當有多個表格時,可以利用書籤將表格分別插入到指定位置。
4.1文檔效果
4.2製作模板並插入標籤
在Word中新建文件,選擇“插入>書籤”,在需要插入表格的位置添加書籤並保存。Aspose.Word可以根據標籤名稱或序號進行查找。
4.3代碼實現
利用上面幾種生成表格的方法將表格插入到不同的書籤處,之後移除書籤。
public static void BuildFile(string savePath,string templatePath= "C:\\Users\\Administrator\\Desktop\\Template.docx")
{
Document doc = new Document(templatePath);//文檔示例
DocumentBuilder builder = new DocumentBuilder(doc);//文檔構造器
Bookmark bookmark1 = doc.Range.Bookmarks["CustomTable"];
if (bookmark1 != null)
{
builder.MoveToBookmark("CustomTable");//移動至書籤
DbTable custom = MakeCustomData();//生成測試數據
CreateCustomTable(doc, builder, custom);//創建表格
bookmark1.Remove();//移除書籤
}
Bookmark bookmark2 = doc.Range.Bookmarks["TreeTable"];
if (bookmark2 != null)
{
builder.MoveToBookmark("TreeTable");//移動至書籤
List<Classify> tree = MakeTreeData();//生成測試數據
CreateTreeTable(doc, builder, tree);//創建表格
bookmark2.Remove();//移除書籤
}
Bookmark bookmark3 = doc.Range.Bookmarks["ListTable"];
if (bookmark3 != null)
{
builder.MoveToBookmark("ListTable");//移動至書籤
List<GoodsModel> list = MakeListData();//生成測試數據
CreateSimpleTable(doc, builder, list);//創建表格
bookmark3.Remove();//移除書籤
}
doc.Save(savePath);//保存文檔
}
拋磚引玉,有更多空間可以挖掘。