Aspose.Words for .NET 教程(九):表格处理完全指南

作者:微信公众号:【架构师老卢】
9-22 16:52
12

Aspose.Words for .NET下载地址 https://soft51.cc/software/175811283999782847

表格是Word文档中展示结构化数据的重要元素。Aspose.Words提供了强大的表格处理功能,支持创建、编辑、格式化和操作各种复杂表格。本教程将系统介绍如何使用Aspose.Words for .NET进行专业的表格处理,包括表格结构设计、样式美化、数据操作等核心功能。

9.1 表格创建与结构设计

表格基本结构

Word表格由以下层次结构组成:

  • Table:表格对象,包含所有行
  • Row:行对象,包含该行的所有单元格
  • Cell:单元格对象,包含实际内容

基础表格创建

using Aspose.Words;
using Aspose.Words.Tables;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 方法一:使用DocumentBuilder创建表格
Table table = builder.StartTable();

// 第一行
builder.InsertCell();
builder.Write("姓名");
builder.InsertCell();
builder.Write("年龄");
builder.InsertCell();
builder.Write("城市");
builder.EndRow();

// 第二行
builder.InsertCell();
builder.Write("张三");
builder.InsertCell();
builder.Write("25");
builder.InsertCell();
builder.Write("北京");
builder.EndRow();

builder.EndTable();

doc.Save("基础表格.docx");

表格结构设计器

public class TableBuilder
{
    private Document document;
    private Table table;
    private DocumentBuilder builder;
    
    public TableBuilder(Document doc)
    {
        document = doc;
        builder = new DocumentBuilder(doc);
    }
    
    // 创建表格
    public TableBuilder CreateTable(int rows, int cols)
    {
        table = builder.StartTable();
        
        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < cols; col++)
            {
                builder.InsertCell();
                builder.Write($"R{row + 1}C{col + 1}");
            }
            builder.EndRow();
        }
        
        builder.EndTable();
        return this;
    }
    
    // 从二维数组创建表格
    public TableBuilder CreateFromArray(string[,] data)
    {
        int rows = data.GetLength(0);
        int cols = data.GetLength(1);
        
        table = builder.StartTable();
        
        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < cols; col++)
            {
                builder.InsertCell();
                builder.Write(data[row, col] ?? "");
            }
            builder.EndRow();
        }
        
        builder.EndTable();
        return this;
    }
    
    // 从列表创建表格
    public TableBuilder CreateFromList<T>(List<T> data, params string[] headers)
    {
        table = builder.StartTable();
        
        // 添加表头
        if (headers != null && headers.Length > 0)
        {
            foreach (string header in headers)
            {
                builder.InsertCell();
                builder.Font.Bold = true;
                builder.Write(header);
            }
            builder.EndRow();
            builder.Font.Bold = false;
        }
        
        // 添加数据行
        foreach (T item in data)
        {
            var properties = typeof(T).GetProperties();
            foreach (var prop in properties.Take(headers?.Length ?? properties.Length))
            {
                builder.InsertCell();
                object value = prop.GetValue(item);
                builder.Write(value?.ToString() ?? "");
            }
            builder.EndRow();
        }
        
        builder.EndTable();
        return this;
    }
    
    public Table GetTable() => table;
}

// 使用示例
public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

Document doc = new Document();
TableBuilder tableBuilder = new TableBuilder(doc);

// 创建员工表格
List<Employee> employees = new List<Employee>
{
    new Employee { Name = "张三", Age = 28, Department = "技术部", Salary = 8000 },
    new Employee { Name = "李四", Age = 32, Department = "销售部", Salary = 7500 },
    new Employee { Name = "王五", Age = 29, Department = "市场部", Salary = 7200 }
};

tableBuilder.CreateFromList(employees, "姓名", "年龄", "部门", "薪资");

doc.Save("结构化表格.docx");

9.2 行列操作(插入、删除、合并)

行列基础操作

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 创建基础表格
Table table = builder.StartTable();
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        builder.InsertCell();
        builder.Write($"({i},{j})");
    }
    builder.EndRow();
}
builder.EndTable();

// 插入新行(在第二行后)
Row newRow = new Row(doc);
for (int i = 0; i < 3; i++)
{
    Cell cell = new Cell(doc);
    cell.AppendChild(new Paragraph(doc));
    cell.FirstParagraph.AppendChild(new Run(doc, $"新行{i}"));
    newRow.AppendChild(cell);
}
table.Rows.Insert(2, newRow);

// 插入新列(在每行的第二列后)
foreach (Row row in table.Rows)
{
    Cell newCell = new Cell(doc);
    newCell.AppendChild(new Paragraph(doc));
    newCell.FirstParagraph.AppendChild(new Run(doc, "新列"));
    row.Cells.Insert(2, newCell);
}

// 删除行(删除第一行)
table.FirstRow.Remove();

// 删除列(删除第一列)
foreach (Row row in table.Rows)
{
    if (row.Cells.Count > 0)
        row.FirstCell.Remove();
}

doc.Save("行列操作.docx");

单元格合并操作

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 创建用于合并演示的表格
Table table = builder.StartTable();

// 第一行 - 合并前三列
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.Write("合并的标题");

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.Write("");

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.Write("");

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write("独立列");
builder.EndRow();

// 第二行 - 垂直合并示例
builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.First;
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write("垂直合并");

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("数据1");

builder.InsertCell();
builder.Write("数据2");

builder.InsertCell();
builder.Write("数据3");
builder.EndRow();

// 第三行 - 继续垂直合并
builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.Previous;
builder.Write("");

builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("数据4");

builder.InsertCell();
builder.Write("数据5");

builder.InsertCell();
builder.Write("数据6");
builder.EndRow();

builder.EndTable();

doc.Save("单元格合并.docx");

9.3 表格样式与格式化

内置样式与自定义样式

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 使用内置表格样式
Table table1 = builder.StartTable();
builder.InsertCell();
builder.Write("产品");
builder.InsertCell();
builder.Write("价格");
builder.InsertCell();
builder.Write("库存");
builder.EndRow();

builder.InsertCell();
builder.Write("笔记本电脑");
builder.InsertCell();
builder.Write("¥5999");
builder.InsertCell();
builder.Write("50");
builder.EndRow();

builder.EndTable();

// 应用内置样式
table1.StyleIdentifier = StyleIdentifier.TableGrid;
table1.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands;

// 自定义表格格式
builder.Writeln(); // 添加间距

Table table2 = builder.StartTable();

// 设置表格整体属性
table2.AutoFit(AutoFitBehavior.FixedColumnWidths);
table2.PreferredWidth = PreferredWidth.FromPercent(100);

// 表头行
builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.DarkBlue;
builder.Font.Color = Color.White;
builder.Font.Bold = true;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Write("部门");

builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.DarkBlue;
builder.Write("人数");

builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.DarkBlue;
builder.Write("平均薪资");
builder.EndRow();

// 重置格式用于数据行
builder.CellFormat.BackgroundPatternColor = Color.White;
builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;

// 数据行1
builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.LightBlue;
builder.Write("技术部");
builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.LightBlue;
builder.Write("25");
builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.LightBlue;
builder.Write("¥8500");
builder.EndRow();

// 数据行2
builder.InsertCell();
builder.Write("销售部");
builder.InsertCell();
builder.Write("18");
builder.InsertCell();
builder.Write("¥7200");
builder.EndRow();

builder.EndTable();

doc.Save("表格样式.docx");

9.4 单元格内容与对齐

单元格内容处理与对齐设置

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// 设置列宽
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
double[] columnWidths = { 100, 150, 100, 120 };

// 表头
string[] headers = { "项目", "描述", "数量", "金额" };
for (int i = 0; i < headers.Length; i++)
{
    builder.InsertCell();
    builder.CellFormat.Width = columnWidths[i];
    builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
    builder.Font.Bold = true;
    builder.CellFormat.BackgroundPatternColor = Color.LightGray;
    builder.Write(headers[i]);
}
builder.EndRow();

// 重置格式
builder.Font.Bold = false;
builder.CellFormat.BackgroundPatternColor = Color.White;

// 数据行 - 演示不同对齐方式
string[,] data = {
    { "商品A", "高质量的商品A,具有优良的性能和可靠的质量保证", "100", "1,250.00" },
    { "商品B", "经济实用的商品B", "50", "875.50" },
    { "商品C", "专业级商品C,适合高端用户使用", "25", "2,100.00" }
};

for (int row = 0; row < data.GetLength(0); row++)
{
    for (int col = 0; col < data.GetLength(1); col++)
    {
        builder.InsertCell();
        builder.CellFormat.Width = columnWidths[col];
        
        // 根据列设置不同的对齐方式
        switch (col)
        {
            case 0: // 项目列 - 左对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                break;
            case 1: // 描述列 - 左对齐,自动换行
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Top;
                break;
            case 2: // 数量列 - 居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                break;
            case 3: // 金额列 - 右对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
                builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                builder.Font.Bold = true;
                break;
        }
        
        builder.Write(data[row, col]);
        
        // 重置粗体格式
        if (col == 3) builder.Font.Bold = false;
    }
    builder.EndRow();
}

// 添加合计行
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Bold = true;
builder.Write("合计:");

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;

builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Bold = true;
builder.Write("¥4,225.50");
builder.EndRow();

builder.EndTable();

doc.Save("单元格对齐.docx");

9.5 表格边框与底纹

边框和底纹设计

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 创建具有复杂边框和底纹的表格
Table table = builder.StartTable();

// 设置表格整体边框
table.SetBorders(LineStyle.Single, 1.0, Color.Black);

// 第一行 - 标题行
builder.InsertCell();
builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Double;
builder.CellFormat.Borders.Bottom.LineWidth = 2.0;
builder.CellFormat.Borders.Bottom.Color = Color.DarkBlue;
builder.CellFormat.BackgroundPatternColor = Color.Navy;
builder.Font.Color = Color.White;
builder.Font.Bold = true;
builder.Write("季度");

builder.InsertCell();
builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Double;
builder.CellFormat.Borders.Bottom.LineWidth = 2.0;
builder.CellFormat.Borders.Bottom.Color = Color.DarkBlue;
builder.CellFormat.BackgroundPatternColor = Color.Navy;
builder.Write("销售额");

builder.InsertCell();
builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Double;
builder.CellFormat.Borders.Bottom.LineWidth = 2.0;
builder.CellFormat.Borders.Bottom.Color = Color.DarkBlue;
builder.CellFormat.BackgroundPatternColor = Color.Navy;
builder.Write("增长率");
builder.EndRow();

// 重置格式
builder.Font.Color = Color.Black;
builder.Font.Bold = false;

// 数据行 - 交替底纹
string[,] data = {
    { "Q1 2024", "¥1,250,000", "+12.5%" },
    { "Q2 2024", "¥1,380,000", "+15.2%" },
    { "Q3 2024", "¥1,420,000", "+8.8%" },
    { "Q4 2024", "¥1,580,000", "+18.6%" }
};

for (int row = 0; row < data.GetLength(0); row++)
{
    Color rowColor = row % 2 == 0 ? Color.LightCyan : Color.White;
    
    for (int col = 0; col < data.GetLength(1); col++)
    {
        builder.InsertCell();
        builder.CellFormat.BackgroundPatternColor = rowColor;
        
        // 特殊边框处理
        if (col == 0) // 第一列左边框加粗
        {
            builder.CellFormat.Borders.Left.LineStyle = LineStyle.Single;
            builder.CellFormat.Borders.Left.LineWidth = 2.0;
            builder.CellFormat.Borders.Left.Color = Color.DarkBlue;
        }
        
        if (col == 2) // 最后一列右边框加粗
        {
            builder.CellFormat.Borders.Right.LineStyle = LineStyle.Single;
            builder.CellFormat.Borders.Right.LineWidth = 2.0;
            builder.CellFormat.Borders.Right.Color = Color.DarkBlue;
            
            // 增长率为正数时显示绿色,负数时显示红色
            if (data[row, col].StartsWith("+"))
                builder.Font.Color = Color.Green;
            else if (data[row, col].StartsWith("-"))
                builder.Font.Color = Color.Red;
        }
        
        builder.Write(data[row, col]);
        builder.Font.Color = Color.Black; // 重置颜色
    }
    builder.EndRow();
}

// 总计行 - 特殊格式
builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.Gold;
builder.CellFormat.Borders.Top.LineStyle = LineStyle.Double;
builder.CellFormat.Borders.Top.LineWidth = 2.0;
builder.Font.Bold = true;
builder.Write("总计");

builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.Gold;
builder.CellFormat.Borders.Top.LineStyle = LineStyle.Double;
builder.CellFormat.Borders.Top.LineWidth = 2.0;
builder.Font.Bold = true;
builder.Write("¥5,630,000");

builder.InsertCell();
builder.CellFormat.BackgroundPatternColor = Color.Gold;
builder.CellFormat.Borders.Top.LineStyle = LineStyle.Double;
builder.CellFormat.Borders.Top.LineWidth = 2.0;
builder.Font.Bold = true;
builder.Font.Color = Color.Green;
builder.Write("+13.8%");
builder.EndRow();

builder.EndTable();

doc.Save("表格边框底纹.docx");

9.6 表格自动调整与分页

自动调整和分页控制

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 创建大表格演示自动调整和分页
Table table = builder.StartTable();

// 设置表格自动调整行为
table.AutoFit(AutoFitBehavior.AutoFitToContents);
table.AllowAutoFit = true;

// 分页设置
table.AllowCellSpacing = true;
table.CellSpacing = 2;

// 创建表头
string[] headers = { "编号", "产品名称", "详细描述", "单价", "库存", "供应商" };
foreach (string header in headers)
{
    builder.InsertCell();
    builder.Font.Bold = true;
    builder.CellFormat.BackgroundPatternColor = Color.LightGray;
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
    builder.Write(header);
}
builder.EndRow();

// 重置格式
builder.Font.Bold = false;
builder.CellFormat.BackgroundPatternColor = Color.White;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;

// 添加大量数据行以演示分页
for (int i = 1; i <= 50; i++)
{
    builder.InsertCell();
    builder.Write($"P{i:000}");
    
    builder.InsertCell();
    builder.Write($"产品 {i}");
    
    builder.InsertCell();
    // 较长的描述文本
    builder.Write($"这是产品{i}的详细描述,包含了产品的各种特性、功能和使用说明。该产品经过严格的质量测试,确保满足客户需求。");
    
    builder.InsertCell();
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
    builder.Write($"¥{(i * 50 + 199):N2}");
    
    builder.InsertCell();
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
    builder.Write($"{100 + i * 5}");
    
    builder.InsertCell();
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
    builder.Write($"供应商{(i % 5) + 1}");
    
    builder.EndRow();
    
    // 每10行设置一次行高
    if (i % 10 == 0)
    {
        Row currentRow = table.LastRow;
        currentRow.RowFormat.Height = 25;
        currentRow.RowFormat.HeightRule = HeightRule.AtLeast;
    }
    
    // 重置段落对齐
    builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
}

builder.EndTable();

// 设置表格分页属性
table.KeepTogether = false; // 允许跨页
foreach (Row row in table.Rows)
{
    row.RowFormat.AllowBreakAcrossPages = true;
    // 表头行不允许分页
    if (row == table.FirstRow)
    {
        row.RowFormat.HeadingFormat = true;
        row.RowFormat.AllowBreakAcrossPages = false;
    }
}

doc.Save("表格自动调整分页.docx");

综合实例:创建财务报表

public class FinancialReportGenerator
{
    private Document document;
    private DocumentBuilder builder;
    
    public FinancialReportGenerator()
    {
        document = new Document();
        builder = new DocumentBuilder(document);
    }
    
    public Document GenerateQuarterlyReport()
    {
        CreateTitle();
        CreateSummaryTable();
        CreateDetailedTable();
        CreateFootnotes();
        
        return document;
    }
    
    private void CreateTitle()
    {
        builder.Font.Size = 16;
        builder.Font.Bold = true;
        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
        builder.Writeln("季度财务报表");
        builder.Font.Size = 12;
        builder.Font.Bold = false;
        builder.Writeln("2024年第三季度");
        builder.Writeln();
    }
    
    private void CreateSummaryTable()
    {
        builder.Font.Bold = true;
        builder.Writeln("一、财务概要");
        builder.Font.Bold = false;
        builder.Writeln();
        
        Table summaryTable = builder.StartTable();
        summaryTable.AutoFit(AutoFitBehavior.FixedColumnWidths);
        summaryTable.PreferredWidth = PreferredWidth.FromPercent(80);
        
        // 表头
        builder.InsertCell();
        builder.CellFormat.Width = 150;
        builder.CellFormat.BackgroundPatternColor = Color.DarkBlue;
        builder.Font.Color = Color.White;
        builder.Font.Bold = true;
        builder.Write("项目");
        
        builder.InsertCell();
        builder.CellFormat.Width = 120;
        builder.CellFormat.BackgroundPatternColor = Color.DarkBlue;
        builder.Write("本季度");
        
        builder.InsertCell();
        builder.CellFormat.Width = 120;
        builder.CellFormat.BackgroundPatternColor = Color.DarkBlue;
        builder.Write("上季度");
        
        builder.InsertCell();
        builder.CellFormat.Width = 120;
        builder.CellFormat.BackgroundPatternColor = Color.DarkBlue;
        builder.Write("同比变化");
        builder.EndRow();
        
        // 重置格式
        builder.Font.Color = Color.Black;
        builder.Font.Bold = false;
        builder.CellFormat.BackgroundPatternColor = Color.White;
        
        // 数据行
        string[,] summaryData = {
            { "总收入", "¥2,450,000", "¥2,180,000", "+12.4%" },
            { "总支出", "¥1,890,000", "¥1,750,000", "+8.0%" },
            { "净利润", "¥560,000", "¥430,000", "+30.2%" },
            { "毛利率", "77.1%", "80.3%", "-3.2%" }
        };
        
        for (int row = 0; row < summaryData.GetLength(0); row++)
        {
            for (int col = 0; col < summaryData.GetLength(1); col++)
            {
                builder.InsertCell();
                
                if (col == 0) // 项目名称
                {
                    builder.Font.Bold = true;
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                }
                else
                {
                    builder.Font.Bold = false;
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
                    
                    // 为增长率添加颜色
                    if (col == 3)
                    {
                        if (summaryData[row, col].StartsWith("+"))
                            builder.Font.Color = Color.Green;
                        else if (summaryData[row, col].StartsWith("-"))
                            builder.Font.Color = Color.Red;
                    }
                }
                
                builder.Write(summaryData[row, col]);
                
                // 重置格式
                builder.Font.Color = Color.Black;
                builder.Font.Bold = false;
            }
            builder.EndRow();
        }
        
        builder.EndTable();
        builder.Writeln();
    }
    
    private void CreateDetailedTable()
    {
        builder.Font.Bold = true;
        builder.Writeln("二、收支明细");
        builder.Font.Bold = false;
        builder.Writeln();
        
        Table detailTable = builder.StartTable();
        detailTable.AutoFit(AutoFitBehavior.AutoFitToWindow);
        detailTable.SetBorders(LineStyle.Single, 0.5, Color.Gray);
        
        // 设置表头
        string[] headers = { "类别", "项目", "预算", "实际", "差额", "完成率" };
        foreach (string header in headers)
        {
            builder.InsertCell();
            builder.CellFormat.BackgroundPatternColor = Color.LightGray;
            builder.Font.Bold = true;
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder.Write(header);
        }
        builder.EndRow();
        
        // 收入部分
        CreateDetailSection("收入", new string[,] {
            { "主营业务收入", "2,200,000", "2,250,000", "+50,000", "102.3%" },
            { "其他业务收入", "150,000", "200,000", "+50,000", "133.3%" }
        });
        
        // 支出部分  
        CreateDetailSection("支出", new string[,] {
            { "人员成本", "800,000", "820,000", "-20,000", "102.5%" },
            { "营销费用", "400,000", "380,000", "+20,000", "95.0%" },
            { "管理费用", "300,000", "290,000", "+10,000", "96.7%" },
            { "研发费用", "350,000", "400,000", "-50,000", "114.3%" }
        });
        
        builder.EndTable();
    }
    
    private void CreateDetailSection(string categoryName, string[,] data)
    {
        // 类别标题行
        builder.InsertCell();
        builder.CellFormat.BackgroundPatternColor = Color.LightBlue;
        builder.CellFormat.HorizontalMerge = CellMerge.First;
        builder.Font.Bold = true;
        builder.Write(categoryName);
        
        for (int i = 1; i < 6; i++)
        {
            builder.InsertCell();
            builder.CellFormat.HorizontalMerge = CellMerge.Previous;
        }
        builder.EndRow();
        
        // 重置格式
        builder.CellFormat.BackgroundPatternColor = Color.White;
        builder.CellFormat.HorizontalMerge = CellMerge.None;
        builder.Font.Bold = false;
        
        // 数据行
        for (int row = 0; row < data.GetLength(0); row++)
        {
            builder.InsertCell();
            builder.Write(""); // 空的类别列
            
            for (int col = 0; col < data.GetLength(1); col++)
            {
                builder.InsertCell();
                
                // 根据列设置对齐方式
                if (col == 0) // 项目名称
                {
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                }
                else // 数值列
                {
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
                    
                    // 为差额和完成率添加颜色
                    if (col == 3) // 差额列
                    {
                        if (data[row, col].StartsWith("+"))
                            builder.Font.Color = Color.Green;
                        else if (data[row, col].StartsWith("-"))
                            builder.Font.Color = Color.Red;
                    }
                    else if (col == 4) // 完成率列
                    {
                        double rate = double.Parse(data[row, col].Replace("%", ""));
                        if (rate >= 100)
                            builder.Font.Color = Color.Green;
                        else if (rate < 90)
                            builder.Font.Color = Color.Red;
                        else
                            builder.Font.Color = Color.Orange;
                    }
                }
                
                builder.Write(data[row, col]);
                builder.Font.Color = Color.Black; // 重置颜色
            }
            builder.EndRow();
        }
    }
    
    private void CreateFootnotes()
    {
        builder.Writeln();
        builder.Font.Size = 10;
        builder.Font.Italic = true;
        builder.Writeln("注:");
        builder.Writeln("1. 所有金额单位为人民币元");
        builder.Writeln("2. 完成率 = 实际/预算 × 100%");
        builder.Writeln("3. 绿色表示超额完成,红色表示未达预期");
        builder.Writeln($"4. 报表生成时间:{DateTime.Now:yyyy-MM-dd HH:mm}");
    }
}

// 使用示例
FinancialReportGenerator generator = new FinancialReportGenerator();
Document report = generator.GenerateQuarterlyReport();
report.Save("季度财务报表.docx");

表格处理工具类

public static class TableHelper
{
    // 表格自动格式化
    public static void ApplyAlternatingRowColors(Table table, Color color1, Color color2, bool includeHeader = true)
    {
        int startRow = includeHeader ? 1 : 0;
        
        for (int i = startRow; i < table.Rows.Count; i++)
        {
            Color rowColor = (i - startRow) % 2 == 0 ? color1 : color2;
            foreach (Cell cell in table.Rows[i].Cells)
            {
                cell.CellFormat.BackgroundPatternColor = rowColor;
            }
        }
    }
    
    // 设置表格边框
    public static void SetTableBorders(Table table, LineStyle style, double width, Color color)
    {
        table.SetBorders(style, width, color);
    }
    
    // 自动调整列宽
    public static void AutoFitColumns(Table table, double[] columnWidths)
    {
        if (table.Rows.Count > 0 && columnWidths.Length == table.FirstRow.Cells.Count)
        {
            for (int col = 0; col < columnWidths.Length; col++)
            {
                foreach (Row row in table.Rows)
                {
                    if (col < row.Cells.Count)
                        row.Cells[col].CellFormat.Width = columnWidths[col];
                }
            }
        }
    }
    
    // 设置表头样式
    public static void FormatTableHeader(Table table, Color backgroundColor, Color fontColor)
    {
        if (table.Rows.Count > 0)
        {
            Row headerRow = table.FirstRow;
            headerRow.RowFormat.HeadingFormat = true;
            
            foreach (Cell cell in headerRow.Cells)
            {
                cell.CellFormat.BackgroundPatternColor = backgroundColor;
                // 设置字体颜色需要遍历段落中的所有Run
                foreach (Paragraph para in cell.Paragraphs)
                {
                    foreach (Run run in para.Runs)
                    {
                        run.Font.Color = fontColor;
                        run.Font.Bold = true;
                    }
                }
            }
        }
    }
    
    // 添加数据验证颜色
    public static void ApplyDataValidationColors(Table table, int columnIndex, 
        Func<string, bool> validationRule, Color validColor, Color invalidColor)
    {
        for (int rowIndex = 1; rowIndex < table.Rows.Count; rowIndex++) // 跳过表头
        {
            Row row = table.Rows[rowIndex];
            if (columnIndex < row.Cells.Count)
            {
                Cell cell = row.Cells[columnIndex];
                string cellText = cell.GetText().Trim();
                
                Color bgColor = validationRule(cellText) ? validColor : invalidColor;
                cell.CellFormat.BackgroundPatternColor = bgColor;
            }
        }
    }
    
    // 表格数据统计
    public static TableStatistics GetTableStatistics(Table table)
    {
        return new TableStatistics
        {
            TotalRows = table.Rows.Count,
            TotalColumns = table.FirstRow?.Cells.Count ?? 0,
            HeaderRows = table.Rows.Cast<Row>().Count(r => r.RowFormat.HeadingFormat),
            TotalCells = table.Rows.Cast<Row>().Sum(r => r.Cells.Count),
            TableWidth = table.PreferredWidth.Value,
            AverageRowHeight = table.Rows.Cast<Row>().Average(r => r.RowFormat.Height)
        };
    }
}

public class TableStatistics
{
    public int TotalRows { get; set; }
    public int TotalColumns { get; set; }
    public int HeaderRows { get; set; }
    public int TotalCells { get; set; }
    public double TableWidth { get; set; }
    public double AverageRowHeight { get; set; }
    
    public override string ToString()
    {
        return $"表格统计:{TotalRows}行 × {TotalColumns}列,共{TotalCells}个单元格";
    }
}

// 使用工具类的示例
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// 创建测试表格
Table testTable = builder.StartTable();
string[,] testData = {
    { "姓名", "年龄", "分数", "等级" },
    { "张三", "25", "85", "B" },
    { "李四", "30", "92", "A" },
    { "王五", "28", "78", "C" },
    { "赵六", "32", "96", "A" }
};

for (int row = 0; row < testData.GetLength(0); row++)
{
    for (int col = 0; col < testData.GetLength(1); col++)
    {
        builder.InsertCell();
        builder.Write(testData[row, col]);
    }
    builder.EndRow();
}
builder.EndTable();

// 应用格式化
TableHelper.ApplyAlternatingRowColors(testTable, Color.White, Color.LightCyan);
TableHelper.FormatTableHeader(testTable, Color.DarkBlue, Color.White);
TableHelper.SetTableBorders(testTable, LineStyle.Single, 1.0, Color.Black);

// 应用数据验证颜色(分数列)
TableHelper.ApplyDataValidationColors(testTable, 2, 
    score => int.TryParse(score, out int s) && s >= 90, 
    Color.LightGreen, Color.LightPink);

// 获取统计信息
TableStatistics stats = TableHelper.GetTableStatistics(testTable);
Console.WriteLine(stats.ToString());

doc.Save("格式化表格.docx");

最佳实践建议

1. 表格设计原则

  • 数据结构清晰:合理组织数据,使用适当的表头和分组
  • 视觉层次分明:通过颜色、边框、字体等区分不同类型的信息
  • 宽度设置合理:根据内容长度合理设置列宽,避免内容被截断

2. 性能优化

  • 批量操作:对于大量数据,使用批量插入而非逐个操作
  • 避免频繁格式更改:预先设定格式,减少运行时修改
  • 合理使用自动调整:根据需求选择合适的自动调整策略

3. 分页控制

  • 表头重复:设置HeadingFormat确保表头在每页重复
  • 避免孤行:合理设置行高和分页属性
  • 整表控制:根据需要决定是否允许表格跨页拆分

本教程全面介绍了Aspose.Words for .NET中的表格处理功能,涵盖了从基础创建到高级格式化的各个方面。通过掌握这些技能,您可以:

  1. 灵活创建表格:支持从数组、对象列表等多种数据源创建表格
  2. 精确控制格式:实现复杂的边框、底纹、对齐等格式效果
  3. 高效数据操作:进行行列插入、删除、合并等结构调整
  4. 专业文档制作:创建如财务报表等专业级别的表格文档
  5. 性能优化处理:在处理大型表格时保持良好的性能表现

表格是Word文档中展示结构化数据的重要工具,熟练掌握表格处理技能对于创建专业文档至关重要。

Aspose.Words for .NET下载地址 https://soft51.cc/software/175811283999782847

相关留言评论
昵称:
邮箱:
阅读排行