05 表格操作 - ZeroHawkeye/wordZero GitHub Wiki

表格操作

WordZero 提供了完整的表格操作功能,包括表格创建、数据操作、结构调整和样式设置。本章将详细介绍如何使用表格功能。

📊 表格创建

基础表格创建

package main

import (
    "github.com/ZeroHawkeye/wordZero/pkg/document"
)

func main() {
    doc := document.New()
    
    // 创建基础表格配置
    config := &document.TableConfig{
        Rows:  3,    // 3行
        Cols:  4,    // 4列
        Width: 8000, // 表格宽度(磅)
    }
    
    // 添加表格到文档
    table := doc.AddTable(config)
    if table != nil {
        fmt.Printf("表格创建成功:%dx%d\n", table.GetRowCount(), table.GetColumnCount())
    }
}

带初始数据的表格

// 创建带初始数据的表格
tableData := [][]string{
    {"姓名", "年龄", "职位", "部门"},
    {"张三", "28", "工程师", "技术部"},
    {"李四", "32", "经理", "销售部"},
}

config := &document.TableConfig{
    Rows:  3,
    Cols:  4,
    Width: 8000,
    Data:  tableData, // 初始数据
}

table := doc.AddTable(config)

📝 表格数据操作

设置和获取单元格内容

// 设置单元格内容
err := table.SetCellText(0, 0, "员工姓名")
if err != nil {
    log.Printf("设置单元格失败: %v", err)
}

// 获取单元格内容
cellText, err := table.GetCellText(1, 1)
if err != nil {
    log.Printf("获取单元格失败: %v", err)
} else {
    fmt.Printf("单元格内容: %s\n", cellText)
}

批量填充数据

// 创建空表格
table := doc.AddTable(&document.TableConfig{
    Rows:  3,
    Cols:  3,
    Width: 6000,
})

// 批量填充数据
data := [][]string{
    {"产品", "价格", "库存"},
    {"笔记本电脑", "5000", "50"},
    {"台式机", "3000", "30"},
}

for i, row := range data {
    for j, cell := range row {
        table.SetCellText(i, j, cell)
    }
}

🔧 表格结构操作

插入和添加行

// 在指定位置插入行
err := table.InsertRow(1, []string{"新员工", "25", "实习生", "技术部"})
if err != nil {
    log.Printf("插入行失败: %v", err)
}

// 在表格末尾添加行
err = table.AppendRow([]string{"王五", "30", "主管", "人事部"})
if err != nil {
    log.Printf("添加行失败: %v", err)
}

插入列

// 在指定位置插入列
columnData := []string{"邮箱", "[email protected]", "[email protected]", "[email protected]"}
err := table.InsertColumn(4, columnData, 2000) // 宽度为2000磅
if err != nil {
    log.Printf("插入列失败: %v", err)
}

删除操作

// 删除行
err := table.DeleteRow(2)
if err != nil {
    log.Printf("删除行失败: %v", err)
}

// 删除列
err = table.DeleteColumn(1)
if err != nil {
    log.Printf("删除列失败: %v", err)
}

🎨 表格样式设置

单元格格式化

// 获取单元格并设置格式
cell, err := table.GetCell(0, 0)
if err != nil {
    log.Printf("获取单元格失败: %v", err)
    return
}

// 设置单元格样式
cell.SetAlignment(document.AlignCenter)
cell.SetBold(true)
cell.SetFontSize(14)
cell.SetFontColor("FF0000") // 红色

表格样式应用

// 应用预定义表格样式
err := table.ApplyStyle("TableGrid")
if err != nil {
    log.Printf("应用表格样式失败: %v", err)
}

// 设置表格边框
table.SetBorder(true)
table.SetBorderWidth(1) // 边框宽度

🔄 表格高级操作

表格复制

// 复制现有表格
newTable := table.Copy()
if newTable != nil {
    fmt.Println("表格复制成功")
}

表格清空

// 清空表格内容(保留结构)
table.Clear()

// 清空指定行
table.ClearRow(1)

// 清空指定列
table.ClearColumn(2)

表格迭代

// 迭代所有单元格
for i := 0; i < table.GetRowCount(); i++ {
    for j := 0; j < table.GetColumnCount(); j++ {
        cellText, err := table.GetCellText(i, j)
        if err == nil {
            fmt.Printf("单元格[%d,%d]: %s\n", i, j, cellText)
        }
    }
}

📖 完整示例

以下是一个展示表格功能的完整示例:

package main

import (
    "fmt"
    "log"
    
    "github.com/ZeroHawkeye/wordZero/pkg/document"
    "github.com/ZeroHawkeye/wordZero/pkg/style"
)

func main() {
    // 创建文档
    doc := document.New()
    
    // 添加标题
    title := doc.AddParagraph("员工信息表")
    title.SetStyle(style.StyleTitle)
    
    // 1. 创建基础员工表格
    fmt.Println("创建员工信息表...")
    
    employeeData := [][]string{
        {"员工编号", "姓名", "部门", "职位", "入职日期"},
        {"E001", "张三", "技术部", "高级工程师", "2023-01-15"},
        {"E002", "李四", "销售部", "销售经理", "2023-02-01"},
        {"E003", "王五", "人事部", "HR专员", "2023-03-10"},
    }
    
    config := &document.TableConfig{
        Rows:  4,
        Cols:  5,
        Width: 10000,
        Data:  employeeData,
    }
    
    table := doc.AddTable(config)
    if table == nil {
        log.Fatal("创建表格失败")
    }
    
    // 2. 设置表头样式
    fmt.Println("设置表头样式...")
    for j := 0; j < table.GetColumnCount(); j++ {
        cell, err := table.GetCell(0, j)
        if err == nil {
            cell.SetBold(true)
            cell.SetAlignment(document.AlignCenter)
            cell.SetFontColor("FFFFFF") // 白色文字
            cell.SetBackgroundColor("4472C4") // 蓝色背景
        }
    }
    
    // 3. 添加新员工
    fmt.Println("添加新员工...")
    newEmployee := []string{"E004", "赵六", "财务部", "会计", "2023-04-01"}
    err := table.AppendRow(newEmployee)
    if err != nil {
        log.Printf("添加员工失败: %v", err)
    }
    
    // 4. 插入联系方式列
    fmt.Println("添加联系方式列...")
    contactData := []string{"联系电话", "13800138001", "13800138002", "13800138003", "13800138004"}
    err = table.InsertColumn(5, contactData, 1500)
    if err != nil {
        log.Printf("插入列失败: %v", err)
    }
    
    // 5. 更新特定员工信息
    fmt.Println("更新员工信息...")
    table.SetCellText(2, 3, "销售总监") // 升职李四
    
    // 6. 设置表格边框和样式
    table.SetBorder(true)
    table.SetBorderWidth(1)
    
    // 7. 创建部门统计表
    doc.AddParagraph("") // 空行
    
    subtitle := doc.AddParagraph("部门统计")
    subtitle.SetStyle(style.StyleHeading2)
    
    deptStats := [][]string{
        {"部门", "人数", "平均薪资"},
        {"技术部", "1", "15000"},
        {"销售部", "1", "12000"},
        {"人事部", "1", "8000"},
        {"财务部", "1", "9000"},
    }
    
    statsConfig := &document.TableConfig{
        Rows:  5,
        Cols:  3,
        Width: 6000,
        Data:  deptStats,
    }
    
    statsTable := doc.AddTable(statsConfig)
    if statsTable != nil {
        // 设置统计表样式
        statsTable.SetBorder(true)
        
        // 设置表头
        for j := 0; j < 3; j++ {
            cell, _ := statsTable.GetCell(0, j)
            cell.SetBold(true)
            cell.SetAlignment(document.AlignCenter)
        }
    }
    
    // 8. 保存文档
    err = doc.Save("employee_table_demo.docx")
    if err != nil {
        log.Fatalf("保存文档失败: %v", err)
    }
    
    fmt.Println("✅ 员工信息表创建完成!")
}

🎯 表格配置选项

TableConfig 结构

type TableConfig struct {
    Rows     int           // 行数
    Cols     int           // 列数  
    Width    int           // 表格总宽度(磅)
    Data     [][]string    // 初始数据(可选)
    Style    string        // 表格样式名称(可选)
    Border   bool          // 是否显示边框
}

常用表格样式

样式名称 描述
TableGrid 基础网格样式
TableNormal 普通表格样式
LightShading 浅色阴影
MediumShading 中等阴影
DarkShading 深色阴影

💡 最佳实践

1. 表格尺寸规划

// ✅ 推荐:合理规划表格宽度
config := &document.TableConfig{
    Width: 8000, // 根据内容调整宽度
}

// ❌ 避免:宽度过小导致内容挤压
config := &document.TableConfig{
    Width: 1000, // 太小
}

2. 错误处理

// ✅ 推荐:检查操作结果
err := table.SetCellText(row, col, text)
if err != nil {
    log.Printf("设置单元格失败: %v", err)
}

// ❌ 避免:忽略错误
table.SetCellText(row, col, text) // 没有错误检查

3. 数据验证

// ✅ 推荐:验证行列索引
if row < table.GetRowCount() && col < table.GetColumnCount() {
    table.SetCellText(row, col, text)
}

⚠️ 注意事项

  1. 索引从0开始: 行列索引都从0开始计数
  2. 数据一致性: 插入行或列时确保数据长度匹配
  3. 内存管理: 大表格操作时注意内存使用
  4. 样式应用顺序: 先创建表格,再应用样式

常见问题

单元格内容不显示

  • 检查行列索引是否正确
  • 确认表格已正确创建
  • 验证数据格式是否正确

表格样式不生效

  • 确认样式名称正确
  • 先创建表格再应用样式
  • 检查样式是否与数据冲突

下一步

掌握表格操作后,您可以继续学习:


表格是文档中重要的数据展示工具,合理使用能够大大提升文档的专业性和可读性!