document

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2025 License: MIT Imports: 13 Imported by: 0

README

Document 包 API 文档

本文档记录了 pkg/document 包中所有可用的公开方法和功能。

核心类型

Document 文档

文档操作方法

文档创建与加载
文档解析功能重大升级 ✨

Open 方法现在支持完整的文档结构解析,包括:

动态元素解析支持

  • 段落解析 (<w:p>): 完整解析段落内容、属性、运行和格式
  • 表格解析 (<w:tbl>): 支持表格结构、网格、行列、单元格内容
  • 节属性解析 (<w:sectPr>): 页面设置、边距、分栏等属性
  • 扩展性设计: 新的解析架构可轻松添加更多元素类型

解析器特性

  • 流式解析: 使用XML流式解析器,内存效率高,适用于大型文档
  • 结构保持: 完整保留文档元素的原始顺序和层次结构
  • 错误恢复: 智能跳过未知或损坏的元素,确保解析过程稳定
  • 深度解析: 支持嵌套结构(如表格中的段落、段落中的运行等)

解析的内容包括

  • 段落文本内容和所有格式属性(字体、大小、颜色、样式等)
  • 表格完整结构(行列定义、单元格内容、表格属性)
  • 页面设置信息(页面尺寸、方向、边距等)
  • 样式引用和属性继承关系
文档保存与导出
文档内容操作
标题段落书签功能 ✨

AddHeadingParagraphWithBookmark 方法现在支持为标题段落添加书签:

书签功能特性

  • 自动书签生成: 为标题段落创建唯一的书签标识
  • 灵活命名: 支持自定义书签名称或留空不添加书签
  • 目录兼容: 生成的书签与目录功能完美兼容,支持导航和超链接
  • Word标准: 符合Microsoft Word的书签格式规范

书签生成规则

  • 书签ID自动生成为 bookmark_{元素索引}_{书签名称} 格式
  • 书签开始标记插入在段落之前
  • 书签结束标记插入在段落之后
  • 支持空书签名称以跳过书签创建
样式管理
页面设置 ✨ 新增功能
页眉页脚操作 ✨ 新增功能
目录功能 ✨ 新增功能
脚注与尾注功能 ✨ 新增功能
列表与编号功能 ✨ 新增功能
结构化文档标签 ✨ 新增功能

段落操作方法

段落格式设置
段落内容操作

文档主体操作方法

元素查询
元素添加

表格操作方法

表格创建
行操作
列操作
单元格操作
单元格文本格式化
单元格合并
单元格特殊属性
表格整体操作
行高设置
表格布局与对齐
行属性设置
表格分页设置
表格样式
边框设置
背景与阴影
单元格遍历迭代器 ✨ 新功能

提供强大的单元格遍历和查找功能:

CellIterator - 单元格迭代器
// 创建迭代器
iterator := table.NewCellIterator()

// 遍历所有单元格
for iterator.HasNext() {
    cellInfo, err := iterator.Next()
    if err != nil {
        break
    }
    fmt.Printf("单元格[%d,%d]: %s\n", cellInfo.Row, cellInfo.Col, cellInfo.Text)
}

// 获取进度
progress := iterator.Progress() // 0.0 - 1.0

// 重置迭代器
iterator.Reset()
ForEach 批量处理
// 遍历所有单元格
err := table.ForEach(func(row, col int, cell *TableCell, text string) error {
    // 处理每个单元格
    return nil
})

// 按行遍历
err := table.ForEachInRow(rowIndex, func(col int, cell *TableCell, text string) error {
    // 处理行中的每个单元格
    return nil
})

// 按列遍历
err := table.ForEachInColumn(colIndex, func(row int, cell *TableCell, text string) error {
    // 处理列中的每个单元格
    return nil
})
范围操作
// 获取指定范围的单元格
cells, err := table.GetCellRange(startRow, startCol, endRow, endCol)
for _, cellInfo := range cells {
    fmt.Printf("单元格[%d,%d]: %s\n", cellInfo.Row, cellInfo.Col, cellInfo.Text)
}
查找功能
// 自定义条件查找
cells, err := table.FindCells(func(row, col int, cell *TableCell, text string) bool {
    return strings.Contains(text, "关键词")
})

// 按文本查找
exactCells, err := table.FindCellsByText("精确匹配", true)
fuzzyCells, err := table.FindCellsByText("模糊", false)
CellInfo 结构
type CellInfo struct {
    Row    int        // 行索引
    Col    int        // 列索引
    Cell   *TableCell // 单元格引用
    Text   string     // 单元格文本
    IsLast bool       // 是否为最后一个单元格
}

工具函数

日志系统
错误处理
域字段工具 ✨ 新增功能

常用配置结构

文本格式
  • TextFormat - 文本格式配置
  • AlignmentType - 对齐类型
  • SpacingConfig - 间距配置
表格配置
  • TableConfig - 表格基础配置
  • CellFormat - 单元格格式
  • RowHeightConfig - 行高配置
  • TableLayoutConfig - 表格布局配置
  • TableStyleConfig - 表格样式配置
  • BorderConfig - 边框配置
  • ShadingConfig - 底纹配置
页面设置配置 ✨ 新增
  • PageSettings - 页面设置配置
  • PageSize - 页面尺寸类型(A4、Letter、Legal、A3、A5、Custom)
  • PageOrientation - 页面方向(Portrait纵向、Landscape横向)
  • SectionProperties - 节属性(包含页面设置信息)
页眉页脚配置 ✨ 新增
  • HeaderFooterType - 页眉页脚类型(Default、First、Even)
  • Header - 页眉结构
  • Footer - 页脚结构
  • HeaderFooterReference - 页眉页脚引用
  • PageNumber - 页码字段
目录配置 ✨ 新增
  • TOCConfig - 目录配置
  • TOCEntry - 目录条目
  • Bookmark - 书签结构
  • BookmarkEnd - 书签结束标记
脚注尾注配置 ✨ 新增
  • FootnoteConfig - 脚注配置
  • FootnoteType - 脚注类型(Footnote脚注、Endnote尾注)
  • FootnoteNumberFormat - 脚注编号格式
  • FootnoteRestart - 脚注重新开始规则
  • FootnotePosition - 脚注位置
  • Footnote - 脚注结构
  • Endnote - 尾注结构
列表编号配置 ✨ 新增
  • ListConfig - 列表配置
  • ListType - 列表类型(Bullet无序、Number有序等)
  • BulletType - 项目符号类型
  • ListItem - 列表项结构
  • Numbering - 编号定义
  • AbstractNum - 抽象编号定义
  • Level - 编号级别
结构化文档标签配置 ✨ 新增
  • SDT - 结构化文档标签
  • SDTProperties - SDT属性
  • SDTContent - SDT内容
域字段配置 ✨ 新增
  • FieldChar - 域字符
  • InstrText - 域指令文本
  • HyperlinkField - 超链接域
  • PageRefField - 页码引用域

使用示例

// 创建新文档
doc := document.New()

// ✨ 新增:页面设置示例
// 设置页面为A4横向
doc.SetPageOrientation(document.OrientationLandscape)

// 设置自定义边距(上下左右:25mm)
doc.SetPageMargins(25, 25, 25, 25)

// 设置自定义页面尺寸(200mm x 300mm)
doc.SetCustomPageSize(200, 300)

// 或者使用完整页面设置
pageSettings := &document.PageSettings{
    Size:           document.PageSizeLetter,
    Orientation:    document.OrientationPortrait,
    MarginTop:      30,
    MarginRight:    20,
    MarginBottom:   30,
    MarginLeft:     20,
    HeaderDistance: 15,
    FooterDistance: 15,
    GutterWidth:    0,
}
doc.SetPageSettings(pageSettings)

// ✨ 新增:页眉页脚示例
// 添加页眉
doc.AddHeader(document.HeaderFooterTypeDefault, "这是页眉")

// 添加带页码的页脚
doc.AddFooterWithPageNumber(document.HeaderFooterTypeDefault, "第", true)

// 设置首页不同
doc.SetDifferentFirstPage(true)

// ✨ 新增:目录示例
// 添加带书签的标题
doc.AddHeadingWithBookmark("第一章 概述", 1, "chapter1")
doc.AddHeadingWithBookmark("1.1 背景", 2, "section1_1")

// 生成目录
tocConfig := document.DefaultTOCConfig()
tocConfig.Title = "目录"
tocConfig.MaxLevel = 3
doc.GenerateTOC(tocConfig)

// ✨ 新增:脚注示例
// 添加脚注
doc.AddFootnote("这是正文内容", "这是脚注内容")

// 添加尾注
doc.AddEndnote("更多说明", "这是尾注内容")

// ✨ 新增:列表示例
// 添加无序列表
doc.AddBulletList("列表项1", 0, document.BulletTypeDot)
doc.AddBulletList("列表项2", 1, document.BulletTypeCircle)

// 添加有序列表
doc.AddNumberedList("第一项", 0, document.ListTypeDecimal)
doc.AddNumberedList("第二项", 0, document.ListTypeDecimal)

// 添加段落
para := doc.AddParagraph("这是一个段落")
para.SetAlignment(document.AlignCenter)

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

// 设置单元格内容
table.SetCellText(0, 0, "标题")

// 保存文档
doc.Save("example.docx")

注意事项

  1. 所有位置索引都是从0开始
  2. 宽度单位使用磅(pt),1磅 = 20twips
  3. 颜色使用十六进制格式,如 "FF0000" 表示红色
  4. 在操作表格前请确保行列索引有效,否则可能返回错误
  5. 页眉页脚类型包括:Default(默认)、First(首页)、Even(偶数页)
  6. 目录功能需要先添加带书签的标题,然后调用生成目录方法
  7. 脚注和尾注会自动编号,支持多种编号格式和重启规则
  8. 列表支持多级嵌套,最多支持9级缩进
  9. 结构化文档标签主要用于目录等特殊功能的实现

Documentation

Overview

Package document 提供了用于创建、编辑和操作 Microsoft Word 文档的 Golang 库。

WordZero 专注于现代的 Office Open XML (OOXML) 格式(.docx 文件), 提供了简单易用的 API 来创建和修改 Word 文档。

主要功能

## 基础功能 - 创建新的 Word 文档 - 打开和解析现有的 .docx 文件 - 添加和格式化文本内容 - 设置段落样式和对齐方式 - 配置字体、颜色和文本格式 - 设置行间距和段落间距 - 错误处理和日志记录

## 高级功能 ✨ 新增 - **页眉页脚**: 支持默认、首页、偶数页不同的页眉页脚设置 - **目录生成**: 基于标题样式自动生成目录,支持超链接和页码 - **脚注尾注**: 完整的脚注和尾注功能,支持多种编号格式 - **列表编号**: 无序列表和有序列表,支持多级嵌套 - **页面设置**: 页面尺寸、方向、边距等完整页面属性设置 - **表格功能**: 强大的表格创建、格式化和样式设置功能 - **样式系统**: 18种预定义样式和自定义样式支持

快速开始

创建一个简单的文档:

doc := document.New()
doc.AddParagraph("Hello, World!")
err := doc.Save("hello.docx")

创建带格式的文档:

doc := document.New()

// 添加格式化标题
titleFormat := &document.TextFormat{
	Bold:      true,
	FontSize:  18,
	FontColor: "FF0000", // 红色
	FontName:  "微软雅黑",
}
title := doc.AddFormattedParagraph("文档标题", titleFormat)
title.SetAlignment(document.AlignCenter)

// 添加正文段落
para := doc.AddParagraph("这是正文内容...")
para.SetSpacing(&document.SpacingConfig{
	LineSpacing:     1.5, // 1.5倍行距
	BeforePara:      12,  // 段前12磅
	AfterPara:       6,   // 段后6磅
	FirstLineIndent: 24,  // 首行缩进24磅
})

err := doc.Save("formatted.docx")

打开现有文档:

doc, err := document.Open("existing.docx")
if err != nil {
	log.Fatal(err)
}

// 读取段落内容
for i, para := range doc.Body.Paragraphs {
	fmt.Printf("段落 %d: ", i+1)
	for _, run := range para.Runs {
		fmt.Print(run.Text.Content)
	}
	fmt.Println()
}

高级功能示例

## 页眉页脚功能

// 添加页眉
doc.AddHeader(document.HeaderFooterTypeDefault, "这是页眉")

// 添加带页码的页脚
doc.AddFooterWithPageNumber(document.HeaderFooterTypeDefault, "第", true)

// 设置首页不同
doc.SetDifferentFirstPage(true)

## 目录生成

// 添加带书签的标题
doc.AddHeadingWithBookmark("第一章 概述", 1, "chapter1")
doc.AddHeadingWithBookmark("1.1 背景", 2, "section1_1")

// 生成目录
tocConfig := document.DefaultTOCConfig()
tocConfig.Title = "目录"
tocConfig.MaxLevel = 3
doc.GenerateTOC(tocConfig)

## 脚注和尾注

// 添加脚注
doc.AddFootnote("这是正文内容", "这是脚注内容")

// 添加尾注
doc.AddEndnote("更多说明", "这是尾注内容")

// 自定义脚注配置
footnoteConfig := &document.FootnoteConfig{
	NumberFormat: document.FootnoteFormatLowerRoman,
	StartNumber:  1,
	RestartEach:  document.FootnoteRestartEachPage,
	Position:     document.FootnotePositionPageBottom,
}
doc.SetFootnoteConfig(footnoteConfig)

## 列表功能

// 无序列表
doc.AddBulletList("列表项1", 0, document.BulletTypeDot)
doc.AddBulletList("子项目", 1, document.BulletTypeCircle)

// 有序列表
doc.AddNumberedList("第一项", 0, document.ListTypeDecimal)
doc.AddNumberedList("第二项", 0, document.ListTypeDecimal)

// 多级列表
items := []document.ListItem{
	{Text: "一级项目", Level: 0, Type: document.ListTypeDecimal},
	{Text: "二级项目", Level: 1, Type: document.ListTypeLowerLetter},
	{Text: "三级项目", Level: 2, Type: document.ListTypeLowerRoman},
}
doc.CreateMultiLevelList(items)

## 页面设置

// 设置页面为A4横向
doc.SetPageOrientation(document.OrientationLandscape)

// 设置页面边距(毫米)
doc.SetPageMargins(25, 25, 25, 25)

// 完整页面设置
pageSettings := &document.PageSettings{
	Size:           document.PageSizeLetter,
	Orientation:    document.OrientationPortrait,
	MarginTop:      30,
	MarginRight:    20,
	MarginBottom:   30,
	MarginLeft:     20,
	HeaderDistance: 15,
	FooterDistance: 15,
	GutterWidth:    0,
}
doc.SetPageSettings(pageSettings)

## 表格功能

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

// 设置单元格内容
table.SetCellText(0, 0, "标题")

// 设置表格样式
table.ApplyTableStyle(&document.TableStyleConfig{
	HeaderRow:    true,
	FirstColumn:  true,
	BandedRows:   true,
	BandedCols:   false,
})

错误处理

库提供了统一的错误处理机制:

doc, err := document.Open("nonexistent.docx")
if err != nil {
	var docErr *document.DocumentError
	if errors.As(err, &docErr) {
		fmt.Printf("操作: %s, 错误: %v\n", docErr.Operation, docErr.Cause)
	}
}

日志记录

可以配置日志级别来控制输出:

// 设置为调试模式
document.SetGlobalLevel(document.LogLevelDebug)

// 只显示错误
document.SetGlobalLevel(document.LogLevelError)

文本格式

TextFormat 结构体支持多种文本格式选项:

format := &document.TextFormat{
	Bold:      true,           // 粗体
	Italic:    true,           // 斜体
	FontSize:  14,             // 字体大小(磅)
	FontColor: "0000FF",       // 字体颜色(十六进制)
	FontName:  "Times New Roman", // 字体名称
}

段落对齐

支持四种对齐方式:

para.SetAlignment(document.AlignLeft)     // 左对齐
para.SetAlignment(document.AlignCenter)   // 居中对齐
para.SetAlignment(document.AlignRight)    // 右对齐
para.SetAlignment(document.AlignJustify)  // 两端对齐

间距配置

可以精确控制段落间距:

config := &document.SpacingConfig{
	LineSpacing:     1.5, // 行间距(倍数)
	BeforePara:      12,  // 段前间距(磅)
	AfterPara:       6,   // 段后间距(磅)
	FirstLineIndent: 24,  // 首行缩进(磅)
}
para.SetSpacing(config)

注意事项

- 字体大小以磅为单位,内部会自动转换为 Word 的半磅单位 - 颜色值使用十六进制格式,不需要 # 前缀 - 间距值以磅为单位,内部会转换为 TWIPs(1磅=20TWIPs) - 所有文本内容都使用 UTF-8 编码 - 页眉页脚类型包括:Default(默认)、First(首页)、Even(偶数页) - 脚注和尾注会自动编号,支持多种编号格式和重启规则 - 列表支持多级嵌套,最多支持9级缩进 - 目录功能需要先添加带书签的标题,然后调用生成目录方法

更多详细信息和示例,请参阅各个类型和函数的文档。

Package document 提供Word文档的核心操作功能

Package document 错误处理

Package document 提供Word文档域字段结构

Package document 提供Word文档脚注和尾注操作功能

Package document 提供Word文档的页眉页脚操作功能

Package document 日志系统

Package document 提供Word文档列表和编号操作功能

Package document 提供Word文档的页面设置功能

Package document 提供Word文档属性操作功能

Package document 提供Word文档的SDT(Structured Document Tag)结构

Package document 提供Word文档的表格操作功能

Package document 提供Word文档目录生成功能

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidDocument 无效文档
	ErrInvalidDocument = errors.New("invalid document")

	// ErrDocumentNotFound 文档未找到
	ErrDocumentNotFound = errors.New("document not found")

	// ErrInvalidFormat 无效格式
	ErrInvalidFormat = errors.New("invalid format")

	// ErrCorruptedFile 文件损坏
	ErrCorruptedFile = errors.New("corrupted file")

	// ErrUnsupportedOperation 不支持的操作
	ErrUnsupportedOperation = errors.New("unsupported operation")
)

预定义错误类型

View Source
var (
	// ErrInvalidPageSettings 无效的页面设置
	ErrInvalidPageSettings = errors.New("invalid page settings")
)

页面设置相关错误

Functions

func Debug

func Debug(msg string)

Debug 全局调试日志

func Debugf

func Debugf(format string, args ...interface{})

Debugf 全局调试日志

func Error

func Error(msg string)

Error 全局错误日志

func Errorf

func Errorf(format string, args ...interface{})

Errorf 全局错误日志

func Info

func Info(msg string)

Info 全局信息日志

func Infof

func Infof(format string, args ...interface{})

Infof 全局信息日志

func SetGlobalLevel

func SetGlobalLevel(level LogLevel)

SetGlobalLevel 设置全局日志级别

func SetGlobalOutput

func SetGlobalOutput(output io.Writer)

SetGlobalOutput 设置全局日志输出

func Warn

func Warn(msg string)

Warn 全局警告日志

func Warnf

func Warnf(format string, args ...interface{})

Warnf 全局警告日志

func WrapError

func WrapError(operation string, err error) error

WrapError 包装错误,添加操作上下文

func WrapErrorWithContext

func WrapErrorWithContext(operation string, err error, context string) error

WrapErrorWithContext 包装错误,添加操作和上下文信息

Types

type AbstractNum

type AbstractNum struct {
	XMLName       xml.Name `xml:"w:abstractNum"`
	AbstractNumID string   `xml:"w:abstractNumId,attr"`
	Levels        []*Level `xml:"w:lvl"`
}

AbstractNum 抽象编号定义

type AbstractNumReference

type AbstractNumReference struct {
	XMLName xml.Name `xml:"w:abstractNumId"`
	Val     string   `xml:"w:val,attr"`
}

AbstractNumReference 抽象编号引用

type AlignmentType

type AlignmentType string

AlignmentType 对齐类型

const (
	// AlignLeft 左对齐
	AlignLeft AlignmentType = "left"
	// AlignCenter 居中对齐
	AlignCenter AlignmentType = "center"
	// AlignRight 右对齐
	AlignRight AlignmentType = "right"
	// AlignJustify 两端对齐
	AlignJustify AlignmentType = "both"
)

type AppProperties

type AppProperties struct {
	XMLName       xml.Name `xml:"Properties"`
	Xmlns         string   `xml:"xmlns,attr"`
	XmlnsVT       string   `xml:"xmlns:vt,attr"`
	Application   string   `xml:"Application,omitempty"`
	DocSecurity   int      `xml:"DocSecurity,omitempty"`
	ScaleCrop     bool     `xml:"ScaleCrop,omitempty"`
	LinksUpToDate bool     `xml:"LinksUpToDate,omitempty"`
	Pages         int      `xml:"Pages,omitempty"`
	Words         int      `xml:"Words,omitempty"`
	Characters    int      `xml:"Characters,omitempty"`
	Paragraphs    int      `xml:"Paragraphs,omitempty"`
	Lines         int      `xml:"Lines,omitempty"`
}

AppProperties 应用程序属性XML结构

type Body

type Body struct {
	XMLName  xml.Name      `xml:"w:body"`
	Elements []interface{} `xml:"-"` // 不序列化此字段,使用自定义方法
}

Body 表示文档主体

func (*Body) AddElement

func (b *Body) AddElement(element interface{})

AddElement 添加元素到文档主体

func (*Body) GetParagraphs

func (b *Body) GetParagraphs() []*Paragraph

GetParagraphs 获取所有段落

func (*Body) GetTables

func (b *Body) GetTables() []*Table

GetTables 获取所有表格

func (*Body) MarshalXML

func (b *Body) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML 自定义XML序列化,按照元素顺序输出

type BodyElement

type BodyElement interface {
	ElementType() string
}

BodyElement 文档主体元素接口

type Bold

type Bold struct {
	XMLName xml.Name `xml:"w:b"`
}

Bold 粗体

type BookmarkEnd

type BookmarkEnd struct {
	XMLName xml.Name `xml:"w:bookmarkEnd"`
	ID      string   `xml:"w:id,attr"`
}

BookmarkEnd 书签结束

func (*BookmarkEnd) ElementType

func (b *BookmarkEnd) ElementType() string

ElementType 返回书签结束元素类型

type BookmarkStart

type BookmarkStart struct {
	XMLName xml.Name `xml:"w:bookmarkStart"`
	ID      string   `xml:"w:id,attr"`
	Name    string   `xml:"w:name,attr"`
}

BookmarkStart 书签开始

func (*BookmarkStart) ElementType

func (b *BookmarkStart) ElementType() string

ElementType 返回书签开始元素类型

type BorderConfig

type BorderConfig struct {
	Style BorderStyle // 边框样式
	Width int         // 边框宽度(1/8磅)
	Color string      // 边框颜色(十六进制,如 "FF0000")
	Space int         // 边框间距
}

BorderConfig 边框配置

type BorderStyle

type BorderStyle string

BorderStyle 边框样式常量

const (
	BorderStyleNone                   BorderStyle = "none"                   // 无边框
	BorderStyleSingle                 BorderStyle = "single"                 // 单线
	BorderStyleThick                  BorderStyle = "thick"                  // 粗线
	BorderStyleDouble                 BorderStyle = "double"                 // 双线
	BorderStyleDotted                 BorderStyle = "dotted"                 // 点线
	BorderStyleDashed                 BorderStyle = "dashed"                 // 虚线
	BorderStyleDotDash                BorderStyle = "dotDash"                // 点划线
	BorderStyleDotDotDash             BorderStyle = "dotDotDash"             // 双点划线
	BorderStyleTriple                 BorderStyle = "triple"                 // 三线
	BorderStyleThinThickSmallGap      BorderStyle = "thinThickSmallGap"      // 细粗细线(小间距)
	BorderStyleThickThinSmallGap      BorderStyle = "thickThinSmallGap"      // 粗细粗线(小间距)
	BorderStyleThinThickThinSmallGap  BorderStyle = "thinThickThinSmallGap"  // 细粗细线(小间距)
	BorderStyleThinThickMediumGap     BorderStyle = "thinThickMediumGap"     // 细粗细线(中间距)
	BorderStyleThickThinMediumGap     BorderStyle = "thickThinMediumGap"     // 粗细粗线(中间距)
	BorderStyleThinThickThinMediumGap BorderStyle = "thinThickThinMediumGap" // 细粗细线(中间距)
	BorderStyleThinThickLargeGap      BorderStyle = "thinThickLargeGap"      // 细粗细线(大间距)
	BorderStyleThickThinLargeGap      BorderStyle = "thickThinLargeGap"      // 粗细粗线(大间距)
	BorderStyleThinThickThinLargeGap  BorderStyle = "thinThickThinLargeGap"  // 细粗细线(大间距)
	BorderStyleWave                   BorderStyle = "wave"                   // 波浪线
	BorderStyleDoubleWave             BorderStyle = "doubleWave"             // 双波浪线
	BorderStyleDashSmallGap           BorderStyle = "dashSmallGap"           // 虚线(小间距)
	BorderStyleDashDotStroked         BorderStyle = "dashDotStroked"         // 划点线
	BorderStyleThreeDEmboss           BorderStyle = "threeDEmboss"           // 3D浮雕
	BorderStyleThreeDEngrave          BorderStyle = "threeDEngrave"          // 3D雕刻
	BorderStyleOutset                 BorderStyle = "outset"                 // 外凸
	BorderStyleInset                  BorderStyle = "inset"                  // 内凹
)

type BulletType

type BulletType string

BulletType 项目符号类型

const (
	// BulletTypeDot 圆点符号
	BulletTypeDot BulletType = "•"
	// BulletTypeCircle 空心圆
	BulletTypeCircle BulletType = "○"
	// BulletTypeSquare 方块
	BulletTypeSquare BulletType = "■"
	// BulletTypeDash 短横线
	BulletTypeDash BulletType = "–"
	// BulletTypeArrow 箭头
	BulletTypeArrow BulletType = "→"
)

type CPText

type CPText struct {
	Text string `xml:",chardata"`
}

CPText CP命名空间文本元素

type CantSplit

type CantSplit struct {
	XMLName xml.Name `xml:"w:cantSplit"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

CantSplit 禁止分割

type CellAlignment

type CellAlignment string

CellAlignment 单元格对齐方式

const (
	// CellAlignLeft 左对齐
	CellAlignLeft CellAlignment = "left"
	// CellAlignCenter 居中对齐
	CellAlignCenter CellAlignment = "center"
	// CellAlignRight 右对齐
	CellAlignRight CellAlignment = "right"
	// CellAlignJustify 两端对齐
	CellAlignJustify CellAlignment = "both"
)

type CellBorderConfig

type CellBorderConfig struct {
	Top      *BorderConfig // 上边框
	Left     *BorderConfig // 左边框
	Bottom   *BorderConfig // 下边框
	Right    *BorderConfig // 右边框
	DiagDown *BorderConfig // 左上到右下对角线
	DiagUp   *BorderConfig // 右上到左下对角线
}

CellBorderConfig 单元格边框配置

type CellFormat

type CellFormat struct {
	TextFormat      *TextFormat           // 文字格式
	HorizontalAlign CellAlignment         // 水平对齐
	VerticalAlign   CellVerticalAlignment // 垂直对齐
	TextDirection   CellTextDirection     // 文字方向
	BackgroundColor string                // 背景颜色
	BorderStyle     string                // 边框样式
	Padding         int                   // 内边距(磅)
}

CellFormat 单元格格式配置

type CellInfo

type CellInfo struct {
	Row    int        // 行索引
	Col    int        // 列索引
	Cell   *TableCell // 单元格引用
	Text   string     // 单元格文本
	IsLast bool       // 是否为最后一个单元格
}

CellInfo 单元格信息

type CellIterator

type CellIterator struct {
	// contains filtered or unexported fields
}

CellIterator 单元格迭代器

func (*CellIterator) Current

func (iter *CellIterator) Current() (int, int)

Current 获取当前位置信息(不移动迭代器)

func (*CellIterator) HasNext

func (iter *CellIterator) HasNext() bool

HasNext 检查是否还有下一个单元格

func (*CellIterator) Next

func (iter *CellIterator) Next() (*CellInfo, error)

Next 获取下一个单元格信息

func (*CellIterator) Progress

func (iter *CellIterator) Progress() float64

Progress 获取迭代进度(0.0-1.0)

func (*CellIterator) Reset

func (iter *CellIterator) Reset()

Reset 重置迭代器到开始位置

func (*CellIterator) Total

func (iter *CellIterator) Total() int

Total 获取总单元格数量

type CellTextDirection

type CellTextDirection string

CellTextDirection 单元格文字方向

const (
	// TextDirectionLR 从左到右(默认)
	TextDirectionLR CellTextDirection = "lrTb"
	// TextDirectionTB 从上到下
	TextDirectionTB CellTextDirection = "tbRl"
	// TextDirectionBT 从下到上
	TextDirectionBT CellTextDirection = "btLr"
	// TextDirectionRL 从右到左
	TextDirectionRL CellTextDirection = "rlTb"
	// TextDirectionTBV 从上到下,垂直显示
	TextDirectionTBV CellTextDirection = "tbLrV"
	// TextDirectionBTV 从下到上,垂直显示
	TextDirectionBTV CellTextDirection = "btLrV"
)

type CellVerticalAlignment

type CellVerticalAlignment string

CellVerticalAlignment 单元格垂直对齐方式

const (
	// CellVAlignTop 顶部对齐
	CellVAlignTop CellVerticalAlignment = "top"
	// CellVAlignCenter 居中对齐
	CellVAlignCenter CellVerticalAlignment = "center"
	// CellVAlignBottom 底部对齐
	CellVAlignBottom CellVerticalAlignment = "bottom"
)

type Color

type Color struct {
	XMLName xml.Name `xml:"w:color"`
	Val     string   `xml:"w:val,attr"`
}

Color 颜色

type Columns

type Columns struct {
	XMLName xml.Name `xml:"w:cols"`
	Space   string   `xml:"w:space,attr,omitempty"` // 栏间距
	Num     string   `xml:"w:num,attr,omitempty"`   // 栏数
}

Columns 分栏设置

type ContentTypes

type ContentTypes struct {
	XMLName   xml.Name   `xml:"Types"`
	Xmlns     string     `xml:"xmlns,attr"`
	Defaults  []Default  `xml:"Default"`
	Overrides []Override `xml:"Override"`
}

ContentTypes 内容类型

type CoreProperties

type CoreProperties struct {
	XMLName       xml.Name `xml:"cp:coreProperties"`
	XmlnsCP       string   `xml:"xmlns:cp,attr"`
	XmlnsDC       string   `xml:"xmlns:dc,attr"`
	XmlnsDCTerms  string   `xml:"xmlns:dcterms,attr"`
	XmlnsDCMIType string   `xml:"xmlns:dcmitype,attr"`
	XmlnsXSI      string   `xml:"xmlns:xsi,attr"`
	Title         *DCText  `xml:"dc:title,omitempty"`
	Subject       *DCText  `xml:"dc:subject,omitempty"`
	Creator       *DCText  `xml:"dc:creator,omitempty"`
	Keywords      *CPText  `xml:"cp:keywords,omitempty"`
	Description   *DCText  `xml:"dc:description,omitempty"`
	Language      *DCText  `xml:"dc:language,omitempty"`
	Category      *CPText  `xml:"cp:category,omitempty"`
	Version       *CPText  `xml:"cp:version,omitempty"`
	Revision      *CPText  `xml:"cp:revision,omitempty"`
	Created       *DCDate  `xml:"dcterms:created,omitempty"`
	Modified      *DCDate  `xml:"dcterms:modified,omitempty"`
	LastPrinted   *DCDate  `xml:"cp:lastPrinted,omitempty"`
}

CoreProperties 核心属性XML结构

type DCDate

type DCDate struct {
	XSIType string    `xml:"xsi:type,attr"`
	Date    time.Time `xml:",chardata"`
}

DCDate DC命名空间日期元素

type DCText

type DCText struct {
	Text string `xml:",chardata"`
}

DCText DC命名空间文本元素

type Default

type Default struct {
	Extension   string `xml:"Extension,attr"`
	ContentType string `xml:"ContentType,attr"`
}

Default 默认内容类型

type DocPart

type DocPart struct {
	XMLName xml.Name `xml:"w:docPart"`
	Val     string   `xml:"w:val,attr"`
}

DocPart 文档部件

type DocPartGallery

type DocPartGallery struct {
	XMLName xml.Name `xml:"w:docPartGallery"`
	Val     string   `xml:"w:val,attr"`
}

DocPartGallery 文档部件库

type DocPartObj

type DocPartObj struct {
	XMLName        xml.Name        `xml:"w:docPartObj"`
	DocPartGallery *DocPartGallery `xml:"w:docPartGallery,omitempty"`
	DocPartUnique  *DocPartUnique  `xml:"w:docPartUnique,omitempty"`
}

DocPartObj 文档部件对象

type DocPartUnique

type DocPartUnique struct {
	XMLName xml.Name `xml:"w:docPartUnique"`
}

DocPartUnique 文档部件唯一标识

type Document

type Document struct {
	// 文档的主要内容
	Body *Body
	// contains filtered or unexported fields
}

Document 表示一个Word文档

func New

func New() *Document

New 创建一个新的空文档

func Open

func Open(filename string) (*Document, error)

Open 打开一个现有的Word文档。

参数 filename 是要打开的 .docx 文件路径。 该函数会解析整个文档结构,包括文本内容、格式和属性。

如果文件不存在、格式错误或解析失败,会返回相应的错误。

示例:

doc, err := document.Open("existing.docx")
if err != nil {
	log.Fatal(err)
}

// 打印所有段落内容
for i, para := range doc.Body.Paragraphs {
	fmt.Printf("段落 %d: ", i+1)
	for _, run := range para.Runs {
		fmt.Print(run.Text.Content)
	}
	fmt.Println()
}

func (*Document) AddBulletList

func (d *Document) AddBulletList(text string, level int, bulletType BulletType) *Paragraph

AddBulletList 添加无序列表项

func (*Document) AddEndnote

func (d *Document) AddEndnote(text string, endnoteText string) error

AddEndnote 添加尾注

func (*Document) AddFooter

func (d *Document) AddFooter(footerType HeaderFooterType, text string) error

AddFooter 添加页脚

func (*Document) AddFooterWithPageNumber

func (d *Document) AddFooterWithPageNumber(footerType HeaderFooterType, text string, showPageNum bool) error

AddFooterWithPageNumber 添加带页码的页脚

func (*Document) AddFootnote

func (d *Document) AddFootnote(text string, footnoteText string) error

AddFootnote 添加脚注

func (*Document) AddFootnoteToRun

func (d *Document) AddFootnoteToRun(run *Run, footnoteText string) error

AddFootnoteToRun 在现有Run中添加脚注引用

func (*Document) AddFormattedParagraph

func (d *Document) AddFormattedParagraph(text string, format *TextFormat) *Paragraph

AddFormattedParagraph 向文档添加一个格式化段落。

参数 text 是段落的文本内容。 参数 format 指定文本格式,如果为 nil 则使用默认格式。

返回新创建段落的指针,可用于进一步设置段落属性。

示例:

doc := document.New()

// 创建格式配置
titleFormat := &document.TextFormat{
	Bold:      true,
	FontSize:  18,
	FontColor: "FF0000", // 红色
	FontName:  "微软雅黑",
}

// 添加格式化标题
title := doc.AddFormattedParagraph("文档标题", titleFormat)
title.SetAlignment(document.AlignCenter)

func (*Document) AddHeader

func (d *Document) AddHeader(headerType HeaderFooterType, text string) error

AddHeader 添加页眉

func (*Document) AddHeaderWithPageNumber

func (d *Document) AddHeaderWithPageNumber(headerType HeaderFooterType, text string, showPageNum bool) error

AddHeaderWithPageNumber 添加带页码的页眉

func (*Document) AddHeadingParagraph

func (d *Document) AddHeadingParagraph(text string, level int) *Paragraph

AddHeadingParagraph 向文档添加一个标题段落。

参数 text 是标题的文本内容。 参数 level 是标题级别(1-9),对应 Heading1 到 Heading9。

返回新创建段落的指针,可用于进一步设置段落属性。 此方法会自动设置正确的样式引用,确保标题能被 Word 导航窗格识别。

示例:

doc := document.New()

// 添加一级标题
h1 := doc.AddHeadingParagraph("第一章:概述", 1)

// 添加二级标题
h2 := doc.AddHeadingParagraph("1.1 背景", 2)

// 添加三级标题
h3 := doc.AddHeadingParagraph("1.1.1 研究目标", 3)

func (*Document) AddHeadingParagraphWithBookmark

func (d *Document) AddHeadingParagraphWithBookmark(text string, level int, bookmarkName string) *Paragraph

AddHeadingParagraphWithBookmark 向文档添加一个带书签的标题段落。

参数 text 是标题的文本内容。 参数 level 是标题级别(1-9),对应 Heading1 到 Heading9。 参数 bookmarkName 是书签名称,如果为空字符串则不添加书签。

返回新创建段落的指针,可用于进一步设置段落属性。 此方法会自动设置正确的样式引用,确保标题能被 Word 导航窗格识别, 并在需要时添加书签以支持目录导航和超链接。

示例:

doc := document.New()

// 添加带书签的一级标题
h1 := doc.AddHeadingParagraphWithBookmark("第一章:概述", 1, "chapter1")

// 添加不带书签的二级标题
h2 := doc.AddHeadingParagraphWithBookmark("1.1 背景", 2, "")

// 添加自动生成书签名的三级标题
h3 := doc.AddHeadingParagraphWithBookmark("1.1.1 研究目标", 3, "auto_bookmark")

func (*Document) AddHeadingWithBookmark

func (d *Document) AddHeadingWithBookmark(text string, level int, bookmarkName string) *Paragraph

AddHeadingWithBookmark 添加带书签的标题

func (*Document) AddListItem

func (d *Document) AddListItem(text string, config *ListConfig) *Paragraph

AddListItem 添加列表项

func (*Document) AddNumberedList

func (d *Document) AddNumberedList(text string, level int, numType ListType) *Paragraph

AddNumberedList 添加有序列表项

func (*Document) AddParagraph

func (d *Document) AddParagraph(text string) *Paragraph

AddParagraph 向文档添加一个普通段落。

参数 text 是段落的文本内容。段落会使用默认格式, 可以后续通过返回的 Paragraph 指针设置格式和属性。

返回新创建段落的指针,可用于进一步格式化。

示例:

doc := document.New()

// 添加普通段落
para := doc.AddParagraph("这是一个段落")

// 设置段落属性
para.SetAlignment(document.AlignCenter)
para.SetSpacing(&document.SpacingConfig{
	LineSpacing: 1.5,
	BeforePara:  12,
})

func (*Document) AddTable

func (d *Document) AddTable(config *TableConfig) *Table

AddTable 将表格添加到文档中

func (*Document) AutoGenerateTOC

func (d *Document) AutoGenerateTOC(config *TOCConfig) error

AutoGenerateTOC 自动生成目录,检测现有文档中的标题

func (*Document) CreateMultiLevelList

func (d *Document) CreateMultiLevelList(items []ListItem) error

CreateMultiLevelList 创建多级列表

func (*Document) CreateTOCSDT

func (d *Document) CreateTOCSDT(title string, maxLevel int) *SDT

CreateTOCSDT 创建目录SDT结构

func (*Document) CreateTable

func (d *Document) CreateTable(config *TableConfig) *Table

CreateTable 创建一个新表格

func (*Document) GenerateTOC

func (d *Document) GenerateTOC(config *TOCConfig) error

GenerateTOC 生成目录

func (*Document) GetDocumentProperties

func (d *Document) GetDocumentProperties() (*DocumentProperties, error)

GetDocumentProperties 获取文档属性

func (*Document) GetEndnoteCount

func (d *Document) GetEndnoteCount() int

GetEndnoteCount 获取尾注数量

func (*Document) GetFootnoteCount

func (d *Document) GetFootnoteCount() int

GetFootnoteCount 获取脚注数量

func (*Document) GetHeadingCount

func (d *Document) GetHeadingCount() map[int]int

GetHeadingCount 获取文档中标题的数量,用于调试

func (*Document) GetPageSettings

func (d *Document) GetPageSettings() *PageSettings

GetPageSettings 获取当前文档的页面设置

func (*Document) GetStyleManager

func (d *Document) GetStyleManager() *style.StyleManager

GetStyleManager 获取文档的样式管理器。

返回文档的样式管理器,可用于访问和管理样式。

示例:

doc := document.New()
styleManager := doc.GetStyleManager()
headingStyle := styleManager.GetStyle("Heading1")

func (*Document) ListHeadings

func (d *Document) ListHeadings() []TOCEntry

ListHeadings 列出文档中所有的标题,用于调试

func (*Document) RemoveEndnote

func (d *Document) RemoveEndnote(endnoteID string) error

RemoveEndnote 删除指定尾注

func (*Document) RemoveFootnote

func (d *Document) RemoveFootnote(footnoteID string) error

RemoveFootnote 删除指定脚注

func (*Document) RestartNumbering

func (d *Document) RestartNumbering(numID string)

RestartNumbering 重新开始编号

func (*Document) Save

func (d *Document) Save(filename string) error

Save 将文档保存到指定的文件路径。

参数 filename 是保存文件的路径,包含文件名和扩展名。 如果目录不存在,会自动创建所需的目录结构。

保存过程包括序列化所有文档内容、压缩为ZIP格式, 并写入到文件系统。

示例:

doc := document.New()
doc.AddParagraph("示例内容")

// 保存到当前目录
err := doc.Save("example.docx")

// 保存到子目录(会自动创建目录)
err = doc.Save("output/documents/example.docx")

if err != nil {
	log.Fatal(err)
}

func (*Document) SetAuthor

func (d *Document) SetAuthor(author string) error

SetAuthor 设置文档作者

func (*Document) SetCategory

func (d *Document) SetCategory(category string) error

SetCategory 设置文档类别

func (*Document) SetCustomPageSize

func (d *Document) SetCustomPageSize(width, height float64) error

SetCustomPageSize 设置自定义页面大小(毫米)

func (*Document) SetDescription

func (d *Document) SetDescription(description string) error

SetDescription 设置文档描述

func (*Document) SetDifferentFirstPage

func (d *Document) SetDifferentFirstPage(different bool)

SetDifferentFirstPage 设置首页不同

func (*Document) SetDocumentProperties

func (d *Document) SetDocumentProperties(properties *DocumentProperties) error

SetDocumentProperties 设置文档属性

func (*Document) SetFootnoteConfig

func (d *Document) SetFootnoteConfig(config *FootnoteConfig) error

SetFootnoteConfig 设置脚注配置

func (*Document) SetGutterWidth

func (d *Document) SetGutterWidth(width float64) error

SetGutterWidth 设置装订线宽度(毫米)

func (*Document) SetHeaderFooterDistance

func (d *Document) SetHeaderFooterDistance(header, footer float64) error

SetHeaderFooterDistance 设置页眉页脚距离(毫米)

func (*Document) SetKeywords

func (d *Document) SetKeywords(keywords string) error

SetKeywords 设置文档关键字

func (*Document) SetPageMargins

func (d *Document) SetPageMargins(top, right, bottom, left float64) error

SetPageMargins 设置页面边距(毫米)

func (*Document) SetPageOrientation

func (d *Document) SetPageOrientation(orientation PageOrientation) error

SetPageOrientation 设置页面方向

func (*Document) SetPageSettings

func (d *Document) SetPageSettings(settings *PageSettings) error

SetPageSettings 设置文档的页面属性

func (*Document) SetPageSize

func (d *Document) SetPageSize(size PageSize) error

SetPageSize 设置页面大小

func (*Document) SetSubject

func (d *Document) SetSubject(subject string) error

SetSubject 设置文档主题

func (*Document) SetTOCStyle

func (d *Document) SetTOCStyle(level int, style *TextFormat) error

SetTOCStyle 设置目录样式

func (*Document) SetTitle

func (d *Document) SetTitle(title string) error

SetTitle 设置文档标题

func (*Document) ToBytes

func (d *Document) ToBytes() ([]byte, error)

ToBytes 将文档转换为字节数组

func (*Document) UpdateStatistics

func (d *Document) UpdateStatistics() error

UpdateStatistics 更新文档统计信息

func (*Document) UpdateTOC

func (d *Document) UpdateTOC() error

UpdateTOC 更新目录

type DocumentError

type DocumentError struct {
	Operation string // 操作名称
	Cause     error  // 原因
	Context   string // 上下文信息
}

DocumentError 文档操作错误

func NewDocumentError

func NewDocumentError(operation string, cause error, context string) *DocumentError

NewDocumentError 创建新的文档错误

func (*DocumentError) Error

func (e *DocumentError) Error() string

Error 实现error接口

func (*DocumentError) Unwrap

func (e *DocumentError) Unwrap() error

Unwrap 解包错误,支持errors.Is和errors.As

type DocumentProperties

type DocumentProperties struct {
	// 核心属性
	Title       string // 文档标题
	Subject     string // 文档主题
	Creator     string // 创建者
	Keywords    string // 关键字
	Description string // 描述
	Language    string // 语言
	Category    string // 类别
	Version     string // 版本
	Revision    string // 修订版本

	// 时间属性
	Created      time.Time // 创建时间
	LastModified time.Time // 最后修改时间
	LastPrinted  time.Time // 最后打印时间

	// 统计属性
	Pages      int // 页数
	Words      int // 字数
	Characters int // 字符数
	Paragraphs int // 段落数
	Lines      int // 行数
}

DocumentProperties 文档属性结构

type Endnote

type Endnote struct {
	XMLName    xml.Name     `xml:"w:endnote"`
	Type       string       `xml:"w:type,attr,omitempty"`
	ID         string       `xml:"w:id,attr"`
	Paragraphs []*Paragraph `xml:"w:p"`
}

Endnote 尾注结构

type EndnoteReference

type EndnoteReference struct {
	XMLName xml.Name `xml:"w:endnoteReference"`
	ID      string   `xml:"w:id,attr"`
}

EndnoteReference 尾注引用

type Endnotes

type Endnotes struct {
	XMLName  xml.Name   `xml:"w:endnotes"`
	Xmlns    string     `xml:"xmlns:w,attr"`
	Endnotes []*Endnote `xml:"w:endnote"`
}

Endnotes 尾注集合

type FieldChar

type FieldChar struct {
	XMLName       xml.Name `xml:"w:fldChar"`
	FieldCharType string   `xml:"w:fldCharType,attr"`
}

FieldChar 域字符

type FontFamily

type FontFamily struct {
	XMLName  xml.Name `xml:"w:rFonts"`
	ASCII    string   `xml:"w:ascii,attr,omitempty"`
	HAnsi    string   `xml:"w:hAnsi,attr,omitempty"`
	EastAsia string   `xml:"w:eastAsia,attr,omitempty"`
	CS       string   `xml:"w:cs,attr,omitempty"`
}

FontFamily 字体族

type FontSize

type FontSize struct {
	XMLName xml.Name `xml:"w:sz"`
	Val     string   `xml:"w:val,attr"`
}

FontSize 字体大小

type Footer struct {
	XMLName     xml.Name     `xml:"w:ftr"`
	XmlnsWPC    string       `xml:"xmlns:wpc,attr"`
	XmlnsMC     string       `xml:"xmlns:mc,attr"`
	XmlnsO      string       `xml:"xmlns:o,attr"`
	XmlnsR      string       `xml:"xmlns:r,attr"`
	XmlnsM      string       `xml:"xmlns:m,attr"`
	XmlnsV      string       `xml:"xmlns:v,attr"`
	XmlnsWP14   string       `xml:"xmlns:wp14,attr"`
	XmlnsWP     string       `xml:"xmlns:wp,attr"`
	XmlnsW10    string       `xml:"xmlns:w10,attr"`
	XmlnsW      string       `xml:"xmlns:w,attr"`
	XmlnsW14    string       `xml:"xmlns:w14,attr"`
	XmlnsW15    string       `xml:"xmlns:w15,attr"`
	XmlnsWPG    string       `xml:"xmlns:wpg,attr"`
	XmlnsWPI    string       `xml:"xmlns:wpi,attr"`
	XmlnsWNE    string       `xml:"xmlns:wne,attr"`
	XmlnsWPS    string       `xml:"xmlns:wps,attr"`
	XmlnsWPSCD  string       `xml:"xmlns:wpsCustomData,attr"`
	MCIgnorable string       `xml:"mc:Ignorable,attr"`
	Paragraphs  []*Paragraph `xml:"w:p"`
}

Footer 页脚结构

type FooterReference

type FooterReference struct {
	XMLName xml.Name `xml:"w:footerReference"`
	Type    string   `xml:"w:type,attr"`
	ID      string   `xml:"r:id,attr"`
}

FooterReference 页脚引用

type Footnote

type Footnote struct {
	XMLName    xml.Name     `xml:"w:footnote"`
	Type       string       `xml:"w:type,attr,omitempty"`
	ID         string       `xml:"w:id,attr"`
	Paragraphs []*Paragraph `xml:"w:p"`
}

Footnote 脚注结构

type FootnoteConfig

type FootnoteConfig struct {
	NumberFormat FootnoteNumberFormat // 编号格式
	StartNumber  int                  // 起始编号
	RestartEach  FootnoteRestart      // 重新开始规则
	Position     FootnotePosition     // 位置
}

FootnoteConfig 脚注配置

func DefaultFootnoteConfig

func DefaultFootnoteConfig() *FootnoteConfig

DefaultFootnoteConfig 返回默认脚注配置

type FootnoteManager

type FootnoteManager struct {
	// contains filtered or unexported fields
}

FootnoteManager 脚注管理器

type FootnoteNumberFormat

type FootnoteNumberFormat string

FootnoteNumberFormat 脚注编号格式

const (
	// FootnoteFormatDecimal 十进制数字
	FootnoteFormatDecimal FootnoteNumberFormat = "decimal"
	// FootnoteFormatLowerRoman 小写罗马数字
	FootnoteFormatLowerRoman FootnoteNumberFormat = "lowerRoman"
	// FootnoteFormatUpperRoman 大写罗马数字
	FootnoteFormatUpperRoman FootnoteNumberFormat = "upperRoman"
	// FootnoteFormatLowerLetter 小写字母
	FootnoteFormatLowerLetter FootnoteNumberFormat = "lowerLetter"
	// FootnoteFormatUpperLetter 大写字母
	FootnoteFormatUpperLetter FootnoteNumberFormat = "upperLetter"
	// FootnoteFormatSymbol 符号
	FootnoteFormatSymbol FootnoteNumberFormat = "symbol"
)

type FootnotePosition

type FootnotePosition string

FootnotePosition 脚注位置

const (
	// FootnotePositionPageBottom 页面底部
	FootnotePositionPageBottom FootnotePosition = "pageBottom"
	// FootnotePositionBeneathText 文本下方
	FootnotePositionBeneathText FootnotePosition = "beneathText"
	// FootnotePositionSectionEnd 节末尾
	FootnotePositionSectionEnd FootnotePosition = "sectEnd"
	// FootnotePositionDocumentEnd 文档末尾
	FootnotePositionDocumentEnd FootnotePosition = "docEnd"
)

type FootnoteReference

type FootnoteReference struct {
	XMLName xml.Name `xml:"w:footnoteReference"`
	ID      string   `xml:"w:id,attr"`
}

FootnoteReference 脚注引用

type FootnoteRestart

type FootnoteRestart string

FootnoteRestart 脚注重新开始规则

const (
	// FootnoteRestartContinuous 连续编号
	FootnoteRestartContinuous FootnoteRestart = "continuous"
	// FootnoteRestartEachSection 每节重新开始
	FootnoteRestartEachSection FootnoteRestart = "eachSect"
	// FootnoteRestartEachPage 每页重新开始
	FootnoteRestartEachPage FootnoteRestart = "eachPage"
)

type FootnoteType

type FootnoteType string

FootnoteType 脚注类型

const (
	// FootnoteTypeFootnote 脚注
	FootnoteTypeFootnote FootnoteType = "footnote"
	// FootnoteTypeEndnote 尾注
	FootnoteTypeEndnote FootnoteType = "endnote"
)

type Footnotes

type Footnotes struct {
	XMLName   xml.Name    `xml:"w:footnotes"`
	Xmlns     string      `xml:"xmlns:w,attr"`
	Footnotes []*Footnote `xml:"w:footnote"`
}

Footnotes 脚注集合

type GridSpan

type GridSpan struct {
	XMLName xml.Name `xml:"w:gridSpan"`
	Val     string   `xml:"w:val,attr"`
}

GridSpan 网格跨度(列合并)

type Header struct {
	XMLName     xml.Name     `xml:"w:hdr"`
	XmlnsWPC    string       `xml:"xmlns:wpc,attr"`
	XmlnsMC     string       `xml:"xmlns:mc,attr"`
	XmlnsO      string       `xml:"xmlns:o,attr"`
	XmlnsR      string       `xml:"xmlns:r,attr"`
	XmlnsM      string       `xml:"xmlns:m,attr"`
	XmlnsV      string       `xml:"xmlns:v,attr"`
	XmlnsWP14   string       `xml:"xmlns:wp14,attr"`
	XmlnsWP     string       `xml:"xmlns:wp,attr"`
	XmlnsW10    string       `xml:"xmlns:w10,attr"`
	XmlnsW      string       `xml:"xmlns:w,attr"`
	XmlnsW14    string       `xml:"xmlns:w14,attr"`
	XmlnsW15    string       `xml:"xmlns:w15,attr"`
	XmlnsWPG    string       `xml:"xmlns:wpg,attr"`
	XmlnsWPI    string       `xml:"xmlns:wpi,attr"`
	XmlnsWNE    string       `xml:"xmlns:wne,attr"`
	XmlnsWPS    string       `xml:"xmlns:wps,attr"`
	XmlnsWPSCD  string       `xml:"xmlns:wpsCustomData,attr"`
	MCIgnorable string       `xml:"mc:Ignorable,attr"`
	Paragraphs  []*Paragraph `xml:"w:p"`
}

Header 页眉结构

type HeaderFooterReference

type HeaderFooterReference struct {
	XMLName xml.Name `xml:"w:headerReference"`
	Type    string   `xml:"w:type,attr"`
	ID      string   `xml:"r:id,attr"`
}

HeaderFooterReference 页眉页脚引用

type HeaderFooterType

type HeaderFooterType string

HeaderFooterType 页眉页脚类型

const (
	// HeaderFooterTypeDefault 默认页眉页脚
	HeaderFooterTypeDefault HeaderFooterType = "default"
	// HeaderFooterTypeFirst 首页页眉页脚
	HeaderFooterTypeFirst HeaderFooterType = "first"
	// HeaderFooterTypeEven 偶数页页眉页脚
	HeaderFooterTypeEven HeaderFooterType = "even"
)

type HideMark

type HideMark struct {
	XMLName xml.Name `xml:"w:hideMark"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

HideMark 隐藏标记

type Hyperlink struct {
	XMLName xml.Name `xml:"w:hyperlink"`
	Anchor  string   `xml:"w:anchor,attr,omitempty"`
	Runs    []Run    `xml:"w:r"`
}

Hyperlink 超链接结构

type HyperlinkField

type HyperlinkField struct {
	BeginChar    FieldChar
	InstrText    InstrText
	SeparateChar FieldChar
	EndChar      FieldChar
}

HyperlinkField 超链接域

func CreateHyperlinkField

func CreateHyperlinkField(anchor string) HyperlinkField

CreateHyperlinkField 创建超链接域

type ILevel

type ILevel struct {
	XMLName xml.Name `xml:"w:ilvl"`
	Val     string   `xml:"w:val,attr"`
}

ILevel 编号级别

type Indentation

type Indentation struct {
	XMLName   xml.Name `xml:"w:ind"`
	FirstLine string   `xml:"w:firstLine,attr,omitempty"`
	Left      string   `xml:"w:left,attr,omitempty"`
	Right     string   `xml:"w:right,attr,omitempty"`
}

Indentation 缩进设置

type InstrText

type InstrText struct {
	XMLName xml.Name `xml:"w:instrText"`
	Space   string   `xml:"xml:space,attr,omitempty"`
	Content string   `xml:",chardata"`
}

InstrText 域指令文本

type Italic

type Italic struct {
	XMLName xml.Name `xml:"w:i"`
}

Italic 斜体

type Justification

type Justification struct {
	XMLName xml.Name `xml:"w:jc"`
	Val     string   `xml:"w:val,attr"`
}

Justification 对齐方式

type KeepLines

type KeepLines struct {
	XMLName xml.Name `xml:"w:keepLines"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

KeepLines 保持行在一起

type KeepNext

type KeepNext struct {
	XMLName xml.Name `xml:"w:keepNext"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

KeepNext 与下一段落保持在一起

type Level

type Level struct {
	XMLName   xml.Name   `xml:"w:lvl"`
	ILevel    string     `xml:"w:ilvl,attr"`
	Start     *Start     `xml:"w:start,omitempty"`
	NumFmt    *NumFmt    `xml:"w:numFmt,omitempty"`
	LevelText *LevelText `xml:"w:lvlText,omitempty"`
	LevelJc   *LevelJc   `xml:"w:lvlJc,omitempty"`
	PPr       *LevelPPr  `xml:"w:pPr,omitempty"`
	RPr       *LevelRPr  `xml:"w:rPr,omitempty"`
}

Level 编号级别

type LevelIndent

type LevelIndent struct {
	XMLName xml.Name `xml:"w:ind"`
	Left    string   `xml:"w:left,attr,omitempty"`
	Hanging string   `xml:"w:hanging,attr,omitempty"`
}

LevelIndent 级别缩进

type LevelJc

type LevelJc struct {
	XMLName xml.Name `xml:"w:lvlJc"`
	Val     string   `xml:"w:val,attr"`
}

LevelJc 级别对齐

type LevelPPr

type LevelPPr struct {
	XMLName xml.Name     `xml:"w:pPr"`
	Ind     *LevelIndent `xml:"w:ind,omitempty"`
}

LevelPPr 级别段落属性

type LevelRPr

type LevelRPr struct {
	XMLName    xml.Name    `xml:"w:rPr"`
	FontFamily *FontFamily `xml:"w:rFonts,omitempty"`
}

LevelRPr 级别文本属性

type LevelText

type LevelText struct {
	XMLName xml.Name `xml:"w:lvlText"`
	Val     string   `xml:"w:val,attr"`
}

LevelText 级别文本

type ListConfig

type ListConfig struct {
	Type         ListType   // 列表类型
	BulletSymbol BulletType // 项目符号(仅用于无序列表)
	StartNumber  int        // 起始编号(仅用于有序列表)
	IndentLevel  int        // 缩进级别(0-8)
}

ListConfig 列表配置

type ListItem

type ListItem struct {
	Text         string     // 文本内容
	Level        int        // 缩进级别
	Type         ListType   // 列表类型
	BulletSymbol BulletType // 项目符号
	StartNumber  int        // 起始编号
}

ListItem 列表项结构

type ListType

type ListType string

ListType 列表类型

const (
	// ListTypeBullet 无序列表(项目符号)
	ListTypeBullet ListType = "bullet"
	// ListTypeNumber 有序列表(数字编号)
	ListTypeNumber ListType = "number"
	// ListTypeDecimal 十进制编号
	ListTypeDecimal ListType = "decimal"
	// ListTypeLowerLetter 小写字母编号
	ListTypeLowerLetter ListType = "lowerLetter"
	// ListTypeUpperLetter 大写字母编号
	ListTypeUpperLetter ListType = "upperLetter"
	// ListTypeLowerRoman 小写罗马数字
	ListTypeLowerRoman ListType = "lowerRoman"
	// ListTypeUpperRoman 大写罗马数字
	ListTypeUpperRoman ListType = "upperRoman"
)

type LogLevel

type LogLevel int

LogLevel 日志级别

const (
	// LogLevelDebug 调试级别
	LogLevelDebug LogLevel = iota
	// LogLevelInfo 信息级别
	LogLevelInfo
	// LogLevelWarn 警告级别
	LogLevelWarn
	// LogLevelError 错误级别
	LogLevelError
	// LogLevelSilent 静默级别
	LogLevelSilent
)

func (LogLevel) String

func (l LogLevel) String() string

String 返回日志级别的字符串表示

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger 日志记录器

func NewLogger

func NewLogger(level LogLevel, output io.Writer) *Logger

NewLogger 创建新的日志记录器

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug 输出调试日志

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf 输出调试日志

func (*Logger) Error

func (l *Logger) Error(msg string)

Error 输出错误日志

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf 输出错误日志

func (*Logger) Info

func (l *Logger) Info(msg string)

Info 输出信息日志

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof 输出信息日志

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*Logger) SetOutput

func (l *Logger) SetOutput(output io.Writer)

SetOutput 设置输出目标

func (*Logger) Warn

func (l *Logger) Warn(msg string)

Warn 输出警告日志

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf 输出警告日志

type NoWrap

type NoWrap struct {
	XMLName xml.Name `xml:"w:noWrap"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

NoWrap 禁止换行

type NumFmt

type NumFmt struct {
	XMLName xml.Name `xml:"w:numFmt"`
	Val     string   `xml:"w:val,attr"`
}

NumFmt 编号格式

type NumID

type NumID struct {
	XMLName xml.Name `xml:"w:numId"`
	Val     string   `xml:"w:val,attr"`
}

NumID 编号ID

type NumInstance

type NumInstance struct {
	XMLName       xml.Name              `xml:"w:num"`
	NumID         string                `xml:"w:numId,attr"`
	AbstractNumID *AbstractNumReference `xml:"w:abstractNumId"`
}

NumInstance 编号实例

type Numbering

type Numbering struct {
	XMLName            xml.Name       `xml:"w:numbering"`
	Xmlns              string         `xml:"xmlns:w,attr"`
	AbstractNums       []*AbstractNum `xml:"w:abstractNum"`
	NumberingInstances []*NumInstance `xml:"w:num"`
}

Numbering 编号定义

type NumberingManager

type NumberingManager struct {
	// contains filtered or unexported fields
}

NumberingManager 编号管理器

type NumberingProperties

type NumberingProperties struct {
	XMLName xml.Name `xml:"w:numPr"`
	ILevel  *ILevel  `xml:"w:ilvl,omitempty"`
	NumID   *NumID   `xml:"w:numId,omitempty"`
}

NumberingProperties 段落编号属性

type Override

type Override struct {
	PartName    string `xml:"PartName,attr"`
	ContentType string `xml:"ContentType,attr"`
}

Override 覆盖内容类型

type PageMargin

type PageMargin struct {
	XMLName xml.Name `xml:"w:pgMar"`
	Top     string   `xml:"w:top,attr"`    // 上边距(twips)
	Right   string   `xml:"w:right,attr"`  // 右边距(twips)
	Bottom  string   `xml:"w:bottom,attr"` // 下边距(twips)
	Left    string   `xml:"w:left,attr"`   // 左边距(twips)
	Header  string   `xml:"w:header,attr"` // 页眉距离(twips)
	Footer  string   `xml:"w:footer,attr"` // 页脚距离(twips)
	Gutter  string   `xml:"w:gutter,attr"` // 装订线(twips)
}

PageMargin 页面边距

type PageNumType

type PageNumType struct {
	XMLName xml.Name `xml:"w:pgNumType"`
	Fmt     string   `xml:"w:fmt,attr,omitempty"`
}

PageNumType 页码类型

type PageNumber

type PageNumber struct {
	XMLName xml.Name `xml:"w:fldSimple"`
	Instr   string   `xml:"w:instr,attr"`
	Text    *Text    `xml:"w:t,omitempty"`
}

PageNumber 页码字段

type PageOrientation

type PageOrientation string

PageOrientation 页面方向类型

const (
	// OrientationPortrait 纵向
	OrientationPortrait PageOrientation = "portrait"
	// OrientationLandscape 横向
	OrientationLandscape PageOrientation = "landscape"
)

type PageRefField

type PageRefField struct {
	BeginChar    FieldChar
	InstrText    InstrText
	SeparateChar FieldChar
	EndChar      FieldChar
}

PageRefField 页码引用域

func CreatePageRefField

func CreatePageRefField(anchor string) PageRefField

CreatePageRefField 创建页码引用域

type PageSettings

type PageSettings struct {
	// 页面尺寸
	Size PageSize
	// 自定义尺寸(当Size为Custom时使用)
	CustomWidth  float64 // 自定义宽度(毫米)
	CustomHeight float64 // 自定义高度(毫米)
	// 页面方向
	Orientation PageOrientation
	// 页面边距(毫米)
	MarginTop    float64
	MarginRight  float64
	MarginBottom float64
	MarginLeft   float64
	// 页眉页脚距离(毫米)
	HeaderDistance float64
	FooterDistance float64
	// 装订线宽度(毫米)
	GutterWidth float64
}

PageSettings 页面设置配置

func DefaultPageSettings

func DefaultPageSettings() *PageSettings

DefaultPageSettings 返回默认页面设置(A4纵向)

type PageSize

type PageSize string

PageSize 页面尺寸类型

const (
	// PageSizeA4 A4纸张 (210mm x 297mm)
	PageSizeA4 PageSize = "A4"
	// PageSizeLetter 美国Letter (8.5" x 11")
	PageSizeLetter PageSize = "Letter"
	// PageSizeLegal 美国Legal (8.5" x 14")
	PageSizeLegal PageSize = "Legal"
	// PageSizeA3 A3纸张 (297mm x 420mm)
	PageSizeA3 PageSize = "A3"
	// PageSizeA5 A5纸张 (148mm x 210mm)
	PageSizeA5 PageSize = "A5"
	// PageSizeCustom 自定义尺寸
	PageSizeCustom PageSize = "Custom"
)

type PageSizeXML

type PageSizeXML struct {
	XMLName xml.Name `xml:"w:pgSz"`
	W       string   `xml:"w:w,attr"`      // 页面宽度(twips)
	H       string   `xml:"w:h,attr"`      // 页面高度(twips)
	Orient  string   `xml:"w:orient,attr"` // 页面方向
}

PageSizeXML 页面尺寸XML结构

type Paragraph

type Paragraph struct {
	XMLName    xml.Name             `xml:"w:p"`
	Properties *ParagraphProperties `xml:"w:pPr,omitempty"`
	Runs       []Run                `xml:"w:r"`
}

Paragraph 表示一个段落

func (*Paragraph) AddFormattedText

func (p *Paragraph) AddFormattedText(text string, format *TextFormat)

AddFormattedText 向段落添加格式化的文本内容。

此方法允许在一个段落中混合使用不同格式的文本。 新的文本会作为一个新的 Run 添加到段落中。

参数 text 是要添加的文本内容。 参数 format 指定文本格式,如果为 nil 则使用默认格式。

示例:

para := doc.AddParagraph("这个段落包含")

// 添加粗体红色文本
para.AddFormattedText("粗体红色", &document.TextFormat{
	Bold: true,
	FontColor: "FF0000",
})

// 添加普通文本
para.AddFormattedText("和普通文本", nil)

// 添加斜体蓝色文本
para.AddFormattedText("以及斜体蓝色", &document.TextFormat{
	Italic: true,
	FontColor: "0000FF",
	FontSize: 14,
})

func (*Paragraph) ElementType

func (p *Paragraph) ElementType() string

ElementType 返回段落元素类型

func (*Paragraph) SetAlignment

func (p *Paragraph) SetAlignment(alignment AlignmentType)

SetAlignment 设置段落的对齐方式。

参数 alignment 指定对齐类型,支持以下值:

  • AlignLeft: 左对齐(默认)
  • AlignCenter: 居中对齐
  • AlignRight: 右对齐
  • AlignJustify: 两端对齐

示例:

para := doc.AddParagraph("居中标题")
para.SetAlignment(document.AlignCenter)

para2 := doc.AddParagraph("右对齐文本")
para2.SetAlignment(document.AlignRight)

func (*Paragraph) SetIndentation

func (p *Paragraph) SetIndentation(firstLineCm, leftCm, rightCm float64)

SetIndentation 设置段落的缩进属性。

参数:

  • firstLineCm: 首行缩进,单位为厘米(可以为负数表示悬挂缩进)
  • leftCm: 左缩进,单位为厘米
  • rightCm: 右缩进,单位为厘米

示例:

para := doc.AddParagraph("这是一个有缩进的段落")
para.SetIndentation(0.5, 0, 0)    // 首行缩进0.5厘米
para.SetIndentation(-0.5, 1, 0)  // 悬挂缩进0.5厘米,左缩进1厘米

func (*Paragraph) SetSpacing

func (p *Paragraph) SetSpacing(config *SpacingConfig)

SetSpacing 设置段落的间距配置。

参数 config 包含各种间距设置,如果为 nil 则不进行任何设置。 配置选项包括:

  • LineSpacing: 行间距倍数(如 1.5 表示1.5倍行距)
  • BeforePara: 段前间距(磅)
  • AfterPara: 段后间距(磅)
  • FirstLineIndent: 首行缩进(磅)

注意:间距值会自动转换为 Word 内部使用的 TWIPs 单位(1磅=20TWIPs)。

示例:

para := doc.AddParagraph("带间距的段落")

// 设置复杂间距
para.SetSpacing(&document.SpacingConfig{
	LineSpacing:     1.5, // 1.5倍行距
	BeforePara:      12,  // 段前12磅
	AfterPara:       6,   // 段后6磅
	FirstLineIndent: 24,  // 首行缩进24磅
})

// 只设置行间距
para2 := doc.AddParagraph("双倍行距")
para2.SetSpacing(&document.SpacingConfig{
	LineSpacing: 2.0,
})

func (*Paragraph) SetStyle

func (p *Paragraph) SetStyle(styleID string)

SetStyle 设置段落的样式。

参数 styleID 是要应用的样式ID,如 "Heading1"、"Normal" 等。 此方法会设置段落的样式引用,确保段落使用指定的样式。

示例:

para := doc.AddParagraph("这是一个段落")
para.SetStyle("Heading2")  // 设置为二级标题样式

type ParagraphProperties

type ParagraphProperties struct {
	XMLName             xml.Name             `xml:"w:pPr"`
	ParagraphStyle      *ParagraphStyle      `xml:"w:pStyle,omitempty"`
	NumberingProperties *NumberingProperties `xml:"w:numPr,omitempty"`
	Spacing             *Spacing             `xml:"w:spacing,omitempty"`
	Justification       *Justification       `xml:"w:jc,omitempty"`
	Indentation         *Indentation         `xml:"w:ind,omitempty"`
	Tabs                *Tabs                `xml:"w:tabs,omitempty"`
}

ParagraphProperties 段落属性

type ParagraphStyle

type ParagraphStyle struct {
	XMLName xml.Name `xml:"w:pStyle"`
	Val     string   `xml:"w:val,attr"`
}

ParagraphStyle 段落样式引用

type Relationship

type Relationship struct {
	ID     string `xml:"Id,attr"`
	Type   string `xml:"Type,attr"`
	Target string `xml:"Target,attr"`
}

Relationship 单个关系

type Relationships

type Relationships struct {
	XMLName       xml.Name       `xml:"Relationships"`
	Xmlns         string         `xml:"xmlns,attr"`
	Relationships []Relationship `xml:"Relationship"`
}

Relationships 文档关系

type RowBreakConfig

type RowBreakConfig struct {
	XMLName   xml.Name   `xml:"w:trPr"`
	CantSplit *CantSplit `xml:"w:cantSplit,omitempty"` // 禁止跨页分割
	TrHeight  *TableRowH `xml:"w:trHeight,omitempty"`  // 行高
	TblHeader *TblHeader `xml:"w:tblHeader,omitempty"` // 标题行重复
}

RowBreakConfig 行分页配置

type RowHeightConfig

type RowHeightConfig struct {
	Height int           // 行高值(磅,1磅=20twips)
	Rule   RowHeightRule // 行高规则
}

RowHeightConfig 行高配置

type RowHeightRule

type RowHeightRule string

RowHeightRule 行高规则

const (
	// RowHeightAuto 自动调整行高
	RowHeightAuto RowHeightRule = "auto"
	// RowHeightMinimum 最小行高
	RowHeightMinimum RowHeightRule = "atLeast"
	// RowHeightExact 固定行高
	RowHeightExact RowHeightRule = "exact"
)

type Run

type Run struct {
	XMLName    xml.Name       `xml:"w:r"`
	Properties *RunProperties `xml:"w:rPr,omitempty"`
	Text       Text           `xml:"w:t,omitempty"`
	FieldChar  *FieldChar     `xml:"w:fldChar,omitempty"`
	InstrText  *InstrText     `xml:"w:instrText,omitempty"`
}

Run 表示一段文本

type RunProperties

type RunProperties struct {
	XMLName    xml.Name    `xml:"w:rPr"`
	Bold       *Bold       `xml:"w:b,omitempty"`
	Italic     *Italic     `xml:"w:i,omitempty"`
	FontSize   *FontSize   `xml:"w:sz,omitempty"`
	Color      *Color      `xml:"w:color,omitempty"`
	FontFamily *FontFamily `xml:"w:rFonts,omitempty"`
}

RunProperties 文本属性

type SDT

type SDT struct {
	XMLName    xml.Name       `xml:"w:sdt"`
	Properties *SDTProperties `xml:"w:sdtPr"`
	EndPr      *SDTEndPr      `xml:"w:sdtEndPr,omitempty"`
	Content    *SDTContent    `xml:"w:sdtContent"`
}

SDT 结构化文档标签,用于目录等特殊功能

func (*SDT) AddTOCEntry

func (sdt *SDT) AddTOCEntry(text string, level int, pageNum int, entryID string)

AddTOCEntry 向目录SDT添加条目

func (*SDT) ElementType

func (s *SDT) ElementType() string

实现BodyElement接口

func (*SDT) FinalizeTOCSDT

func (sdt *SDT) FinalizeTOCSDT()

FinalizeTOCSDT 完成目录SDT构建

type SDTColor

type SDTColor struct {
	XMLName xml.Name `xml:"w15:color"`
	Val     string   `xml:"w:val,attr"`
}

SDTColor SDT颜色

type SDTContent

type SDTContent struct {
	XMLName  xml.Name      `xml:"w:sdtContent"`
	Elements []interface{} `xml:"-"` // 使用自定义序列化
}

SDTContent SDT内容

func (*SDTContent) MarshalXML

func (s *SDTContent) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML 自定义XML序列化

type SDTEndPr

type SDTEndPr struct {
	XMLName xml.Name       `xml:"w:sdtEndPr"`
	RunPr   *RunProperties `xml:"w:rPr,omitempty"`
}

SDTEndPr SDT结束属性

type SDTID

type SDTID struct {
	XMLName xml.Name `xml:"w:id"`
	Val     string   `xml:"w:val,attr"`
}

SDTID SDT标识符

type SDTPlaceholder

type SDTPlaceholder struct {
	XMLName xml.Name `xml:"w:placeholder"`
	DocPart *DocPart `xml:"w:docPart,omitempty"`
}

SDTPlaceholder SDT占位符

type SDTProperties

type SDTProperties struct {
	XMLName     xml.Name        `xml:"w:sdtPr"`
	RunPr       *RunProperties  `xml:"w:rPr,omitempty"`
	ID          *SDTID          `xml:"w:id,omitempty"`
	Color       *SDTColor       `xml:"w15:color,omitempty"`
	DocPartObj  *DocPartObj     `xml:"w:docPartObj,omitempty"`
	Placeholder *SDTPlaceholder `xml:"w:placeholder,omitempty"`
}

SDTProperties SDT属性

type SectionProperties

type SectionProperties struct {
	XMLName          xml.Name                 `xml:"w:sectPr"`
	XmlnsR           string                   `xml:"xmlns:r,attr,omitempty"`
	PageSize         *PageSizeXML             `xml:"w:pgSz,omitempty"`
	PageMargins      *PageMargin              `xml:"w:pgMar,omitempty"`
	Columns          *Columns                 `xml:"w:cols,omitempty"`
	HeaderReferences []*HeaderFooterReference `xml:"w:headerReference,omitempty"`
	FooterReferences []*FooterReference       `xml:"w:footerReference,omitempty"`
	TitlePage        *TitlePage               `xml:"w:titlePg,omitempty"`
	PageNumType      *PageNumType             `xml:"w:pgNumType,omitempty"`
}

SectionProperties 节属性,包含页面设置信息

func (*SectionProperties) ElementType

func (s *SectionProperties) ElementType() string

ElementType 返回节属性元素类型

type ShadingConfig

type ShadingConfig struct {
	Pattern         ShadingPattern // 底纹图案
	ForegroundColor string         // 前景色(十六进制)
	BackgroundColor string         // 背景色(十六进制)
}

ShadingConfig 底纹配置

type ShadingPattern

type ShadingPattern string

ShadingPattern 底纹图案类型

const (
	ShadingPatternClear             ShadingPattern = "clear"             // 透明/实色
	ShadingPatternSolid             ShadingPattern = "clear"             // 实色(使用clear实现)
	ShadingPatternPct5              ShadingPattern = "pct5"              // 5%
	ShadingPatternPct10             ShadingPattern = "pct10"             // 10%
	ShadingPatternPct20             ShadingPattern = "pct20"             // 20%
	ShadingPatternPct25             ShadingPattern = "pct25"             // 25%
	ShadingPatternPct30             ShadingPattern = "pct30"             // 30%
	ShadingPatternPct40             ShadingPattern = "pct40"             // 40%
	ShadingPatternPct50             ShadingPattern = "pct50"             // 50%
	ShadingPatternPct60             ShadingPattern = "pct60"             // 60%
	ShadingPatternPct70             ShadingPattern = "pct70"             // 70%
	ShadingPatternPct75             ShadingPattern = "pct75"             // 75%
	ShadingPatternPct80             ShadingPattern = "pct80"             // 80%
	ShadingPatternPct90             ShadingPattern = "pct90"             // 90%
	ShadingPatternHorzStripe        ShadingPattern = "horzStripe"        // 水平条纹
	ShadingPatternVertStripe        ShadingPattern = "vertStripe"        // 垂直条纹
	ShadingPatternReverseDiagStripe ShadingPattern = "reverseDiagStripe" // 反对角条纹
	ShadingPatternDiagStripe        ShadingPattern = "diagStripe"        // 对角条纹
	ShadingPatternHorzCross         ShadingPattern = "horzCross"         // 水平十字
	ShadingPatternDiagCross         ShadingPattern = "diagCross"         // 对角十字
)

type Spacing

type Spacing struct {
	XMLName xml.Name `xml:"w:spacing"`
	Before  string   `xml:"w:before,attr,omitempty"`
	After   string   `xml:"w:after,attr,omitempty"`
	Line    string   `xml:"w:line,attr,omitempty"`
}

Spacing 间距设置

type SpacingConfig

type SpacingConfig struct {
	LineSpacing     float64 // 行间距(倍数,如1.5表示1.5倍行距)
	BeforePara      int     // 段前间距(磅)
	AfterPara       int     // 段后间距(磅)
	FirstLineIndent int     // 首行缩进(磅)
}

SpacingConfig 间距配置

type Start

type Start struct {
	XMLName xml.Name `xml:"w:start"`
	Val     string   `xml:"w:val,attr"`
}

Start 起始编号

type TOCConfig

type TOCConfig struct {
	Title        string // 目录标题,默认为"目录"
	MaxLevel     int    // 最大级别,默认为3(显示1-3级标题)
	ShowPageNum  bool   // 是否显示页码,默认为true
	RightAlign   bool   // 页码是否右对齐,默认为true
	UseHyperlink bool   // 是否使用超链接,默认为true
	DotLeader    bool   // 是否使用点状引导线,默认为true
}

TOCConfig 目录配置

func DefaultTOCConfig

func DefaultTOCConfig() *TOCConfig

DefaultTOCConfig 返回默认目录配置

type TOCEntry

type TOCEntry struct {
	Text       string // 条目文本
	Level      int    // 级别(1-9)
	PageNum    int    // 页码
	BookmarkID string // 书签ID(用于超链接)
}

TOCEntry 目录条目

type TOCField

type TOCField struct {
	XMLName xml.Name `xml:"w:fldSimple"`
	Instr   string   `xml:"w:instr,attr"`
	Runs    []Run    `xml:"w:r"`
}

TOCField 目录域

type Tab

type Tab struct {
	XMLName xml.Name `xml:"w:tab"`
}

Tab 制表符

type TabDef

type TabDef struct {
	XMLName xml.Name `xml:"w:tab"`
	Val     string   `xml:"w:val,attr"`
	Leader  string   `xml:"w:leader,attr,omitempty"`
	Pos     string   `xml:"w:pos,attr"`
}

TabDef 制表符定义

type Table

type Table struct {
	XMLName    xml.Name         `xml:"w:tbl"`
	Properties *TableProperties `xml:"w:tblPr,omitempty"`
	Grid       *TableGrid       `xml:"w:tblGrid,omitempty"`
	Rows       []TableRow       `xml:"w:tr"`
}

Table 表示一个表格

func (*Table) AddCellFormattedText

func (t *Table) AddCellFormattedText(row, col int, text string, format *TextFormat) error

AddCellFormattedText 添加格式化文本到单元格(追加模式)

func (*Table) AppendColumn

func (t *Table) AppendColumn(data []string, width int) error

AppendColumn 在表格末尾添加列

func (*Table) AppendRow

func (t *Table) AppendRow(data []string) error

AppendRow 在表格末尾添加行

func (*Table) ApplyTableStyle

func (t *Table) ApplyTableStyle(config *TableStyleConfig) error

ApplyTableStyle 应用表格样式

func (*Table) ClearCellContent

func (t *Table) ClearCellContent(row, col int) error

ClearCellContent 清空单元格内容但保留格式

func (*Table) ClearCellFormat

func (t *Table) ClearCellFormat(row, col int) error

ClearCellFormat 清空单元格格式但保留内容

func (*Table) ClearTable

func (t *Table) ClearTable()

ClearTable 清空表格内容(保留结构)

func (*Table) CopyTable

func (t *Table) CopyTable() *Table

CopyTable 复制表格

func (*Table) CreateCustomTableStyle

func (t *Table) CreateCustomTableStyle(styleID, styleName string,
	borderConfig *TableBorderConfig,
	shadingConfig *ShadingConfig,
	firstRowBold bool) error

CreateCustomTableStyle 创建自定义表格样式

func (*Table) DeleteColumn

func (t *Table) DeleteColumn(colIndex int) error

DeleteColumn 删除指定列

func (*Table) DeleteColumns

func (t *Table) DeleteColumns(startIndex, endIndex int) error

DeleteColumns 删除指定范围的列

func (*Table) DeleteRow

func (t *Table) DeleteRow(rowIndex int) error

DeleteRow 删除指定行

func (*Table) DeleteRows

func (t *Table) DeleteRows(startIndex, endIndex int) error

DeleteRows 删除指定范围的行

func (*Table) ElementType

func (t *Table) ElementType() string

ElementType 返回表格元素类型

func (*Table) FindCells

func (t *Table) FindCells(predicate func(row, col int, cell *TableCell, text string) bool) ([]*CellInfo, error)

FindCells 查找满足条件的单元格

func (*Table) FindCellsByText

func (t *Table) FindCellsByText(searchText string, exactMatch bool) ([]*CellInfo, error)

FindCellsByText 根据文本内容查找单元格

func (*Table) ForEach

func (t *Table) ForEach(fn func(row, col int, cell *TableCell, text string) error) error

ForEach 遍历所有单元格,对每个单元格执行指定函数

func (*Table) ForEachInColumn

func (t *Table) ForEachInColumn(colIndex int, fn func(row int, cell *TableCell, text string) error) error

ForEachInColumn 遍历指定列的所有单元格

func (*Table) ForEachInRow

func (t *Table) ForEachInRow(rowIndex int, fn func(col int, cell *TableCell, text string) error) error

ForEachInRow 遍历指定行的所有单元格

func (*Table) GetCell

func (t *Table) GetCell(row, col int) (*TableCell, error)

GetCell 获取指定位置的单元格

func (*Table) GetCellFormat

func (t *Table) GetCellFormat(row, col int) (*CellFormat, error)

GetCellFormat 获取单元格格式信息

func (*Table) GetCellRange

func (t *Table) GetCellRange(startRow, startCol, endRow, endCol int) ([]*CellInfo, error)

GetCellRange 获取指定范围内的所有单元格

func (*Table) GetCellText

func (t *Table) GetCellText(row, col int) (string, error)

GetCellText 获取单元格文本

func (*Table) GetCellTextDirection

func (t *Table) GetCellTextDirection(row, col int) (CellTextDirection, error)

GetCellTextDirection 获取单元格文字方向

func (*Table) GetColumnCount

func (t *Table) GetColumnCount() int

GetColumnCount 获取表格列数

func (*Table) GetMergedCellInfo

func (t *Table) GetMergedCellInfo(row, col int) (map[string]interface{}, error)

GetMergedCellInfo 获取合并单元格信息

func (*Table) GetRowCount

func (t *Table) GetRowCount() int

GetRowCount 获取表格行数

func (*Table) GetRowHeight

func (t *Table) GetRowHeight(rowIndex int) (*RowHeightConfig, error)

GetRowHeight 获取行高配置

func (*Table) GetTableBreakInfo

func (t *Table) GetTableBreakInfo() map[string]interface{}

GetTableBreakInfo 获取表格分页信息

func (*Table) GetTableLayout

func (t *Table) GetTableLayout() *TableLayoutConfig

GetTableLayout 获取表格布局配置

func (*Table) InsertColumn

func (t *Table) InsertColumn(position int, data []string, width int) error

InsertColumn 在指定位置插入列

func (*Table) InsertRow

func (t *Table) InsertRow(position int, data []string) error

InsertRow 在指定位置插入行

func (*Table) IsCellMerged

func (t *Table) IsCellMerged(row, col int) (bool, error)

IsCellMerged 检查单元格是否被合并

func (*Table) IsRowHeader

func (t *Table) IsRowHeader(rowIndex int) (bool, error)

IsRowHeader 检查行是否为标题行

func (*Table) IsRowKeepTogether

func (t *Table) IsRowKeepTogether(rowIndex int) (bool, error)

IsRowKeepTogether 检查行是否禁止跨页分割

func (*Table) MergeCellsHorizontal

func (t *Table) MergeCellsHorizontal(row, startCol, endCol int) error

MergeCellsHorizontal 水平合并单元格(合并列)

func (*Table) MergeCellsRange

func (t *Table) MergeCellsRange(startRow, endRow, startCol, endCol int) error

MergeCellsRange 合并单元格区域(多行多列)

func (*Table) MergeCellsVertical

func (t *Table) MergeCellsVertical(startRow, endRow, col int) error

MergeCellsVertical 垂直合并单元格(合并行)

func (*Table) NewCellIterator

func (t *Table) NewCellIterator() *CellIterator

NewCellIterator 创建新的单元格迭代器

func (*Table) RemoveCellBorders

func (t *Table) RemoveCellBorders(row, col int) error

RemoveCellBorders 移除单元格边框

func (*Table) RemoveTableBorders

func (t *Table) RemoveTableBorders() error

RemoveTableBorders 移除表格边框

func (*Table) SetAlternatingRowColors

func (t *Table) SetAlternatingRowColors(evenRowColor, oddRowColor string) error

SetAlternatingRowColors 设置奇偶行颜色交替

func (*Table) SetCellBorders

func (t *Table) SetCellBorders(row, col int, config *CellBorderConfig) error

SetCellBorders 设置单元格边框

func (*Table) SetCellFormat

func (t *Table) SetCellFormat(row, col int, format *CellFormat) error

SetCellFormat 设置单元格格式

func (*Table) SetCellFormattedText

func (t *Table) SetCellFormattedText(row, col int, text string, format *TextFormat) error

SetCellFormattedText 设置单元格富文本内容

func (*Table) SetCellPadding

func (t *Table) SetCellPadding(row, col int, padding int) error

SetCellPadding 设置单元格内边距

func (*Table) SetCellShading

func (t *Table) SetCellShading(row, col int, config *ShadingConfig) error

SetCellShading 设置单元格背景

func (*Table) SetCellText

func (t *Table) SetCellText(row, col int, text string) error

SetCellText 设置单元格文本

func (*Table) SetCellTextDirection

func (t *Table) SetCellTextDirection(row, col int, direction CellTextDirection) error

SetCellTextDirection 设置单元格文字方向

func (*Table) SetHeaderRows

func (t *Table) SetHeaderRows(startRow, endRow int) error

SetHeaderRows 设置表格标题行范围

func (*Table) SetRowAsHeader

func (t *Table) SetRowAsHeader(rowIndex int, isHeader bool) error

SetRowAsHeader 设置行为重复的标题行

func (*Table) SetRowHeight

func (t *Table) SetRowHeight(rowIndex int, config *RowHeightConfig) error

SetRowHeight 设置行高

func (*Table) SetRowHeightRange

func (t *Table) SetRowHeightRange(startRow, endRow int, config *RowHeightConfig) error

SetRowHeightRange 批量设置行高

func (*Table) SetRowKeepTogether

func (t *Table) SetRowKeepTogether(rowIndex int, keepTogether bool) error

SetRowKeepTogether 设置行禁止跨页分割

func (*Table) SetRowKeepWithNext

func (t *Table) SetRowKeepWithNext(rowIndex int, keepWithNext bool) error

SetRowKeepWithNext 设置行与下一行保持在同一页

func (*Table) SetTableAlignment

func (t *Table) SetTableAlignment(alignment TableAlignment) error

SetTableAlignment 设置表格对齐方式(快捷方法)

func (*Table) SetTableBorders

func (t *Table) SetTableBorders(config *TableBorderConfig) error

SetTableBorders 设置表格边框

func (*Table) SetTableLayout

func (t *Table) SetTableLayout(config *TableLayoutConfig) error

SetTableLayout 设置表格布局和定位

func (*Table) SetTablePageBreak

func (t *Table) SetTablePageBreak(config *TablePageBreakConfig) error

SetTablePageBreak 设置表格分页控制

func (*Table) SetTableShading

func (t *Table) SetTableShading(config *ShadingConfig) error

SetTableShading 设置表格背景

func (*Table) UnmergeCells

func (t *Table) UnmergeCells(row, col int) error

UnmergeCells 取消单元格合并

type TableAlignment

type TableAlignment string

TableAlignment 表格对齐类型

const (
	// TableAlignLeft 左对齐
	TableAlignLeft TableAlignment = "left"
	// TableAlignCenter 居中对齐
	TableAlignCenter TableAlignment = "center"
	// TableAlignRight 右对齐
	TableAlignRight TableAlignment = "right"
	// TableAlignInside 内侧对齐
	TableAlignInside TableAlignment = "inside"
	// TableAlignOutside 外侧对齐
	TableAlignOutside TableAlignment = "outside"
)

type TableBorder

type TableBorder struct {
	Val        string `xml:"w:val,attr"`                  // 边框样式
	Sz         string `xml:"w:sz,attr"`                   // 边框粗细(1/8磅)
	Space      string `xml:"w:space,attr"`                // 边框间距
	Color      string `xml:"w:color,attr"`                // 边框颜色
	ThemeColor string `xml:"w:themeColor,attr,omitempty"` // 主题颜色
}

TableBorder 边框定义

type TableBorderConfig

type TableBorderConfig struct {
	Top     *BorderConfig // 上边框
	Left    *BorderConfig // 左边框
	Bottom  *BorderConfig // 下边框
	Right   *BorderConfig // 右边框
	InsideH *BorderConfig // 内部水平边框
	InsideV *BorderConfig // 内部垂直边框
}

TableBorderConfig 表格边框配置

type TableBorders

type TableBorders struct {
	XMLName xml.Name     `xml:"w:tblBorders"`
	Top     *TableBorder `xml:"w:top,omitempty"`     // 上边框
	Left    *TableBorder `xml:"w:left,omitempty"`    // 左边框
	Bottom  *TableBorder `xml:"w:bottom,omitempty"`  // 下边框
	Right   *TableBorder `xml:"w:right,omitempty"`   // 右边框
	InsideH *TableBorder `xml:"w:insideH,omitempty"` // 内部水平边框
	InsideV *TableBorder `xml:"w:insideV,omitempty"` // 内部垂直边框
}

TableBorders 表格边框

type TableBreakRule

type TableBreakRule string

TableBreakRule 表格分页规则

const (
	// BreakAuto 自动分页(默认)
	BreakAuto TableBreakRule = "auto"
	// BreakPage 强制分页
	BreakPage TableBreakRule = "page"
	// BreakColumn 强制分栏
	BreakColumn TableBreakRule = "column"
)

type TableCell

type TableCell struct {
	XMLName    xml.Name             `xml:"w:tc"`
	Properties *TableCellProperties `xml:"w:tcPr,omitempty"`
	Paragraphs []Paragraph          `xml:"w:p"`
}

TableCell 表格单元格

type TableCellBorder

type TableCellBorder struct {
	Val        string `xml:"w:val,attr"`                  // 边框样式
	Sz         string `xml:"w:sz,attr"`                   // 边框粗细(1/8磅)
	Space      string `xml:"w:space,attr"`                // 边框间距
	Color      string `xml:"w:color,attr"`                // 边框颜色
	ThemeColor string `xml:"w:themeColor,attr,omitempty"` // 主题颜色
}

TableCellBorder 单元格边框定义

type TableCellBorders

type TableCellBorders struct {
	XMLName xml.Name         `xml:"w:tcBorders"`
	Top     *TableCellBorder `xml:"w:top,omitempty"`     // 上边框
	Left    *TableCellBorder `xml:"w:left,omitempty"`    // 左边框
	Bottom  *TableCellBorder `xml:"w:bottom,omitempty"`  // 下边框
	Right   *TableCellBorder `xml:"w:right,omitempty"`   // 右边框
	InsideH *TableCellBorder `xml:"w:insideH,omitempty"` // 内部水平边框
	InsideV *TableCellBorder `xml:"w:insideV,omitempty"` // 内部垂直边框
	TL2BR   *TableCellBorder `xml:"w:tl2br,omitempty"`   // 左上到右下对角线
	TR2BL   *TableCellBorder `xml:"w:tr2bl,omitempty"`   // 右上到左下对角线
}

TableCellBorders 单元格边框

type TableCellMargins

type TableCellMargins struct {
	XMLName xml.Name        `xml:"w:tblCellMar"`
	Top     *TableCellSpace `xml:"w:top,omitempty"`
	Left    *TableCellSpace `xml:"w:left,omitempty"`
	Bottom  *TableCellSpace `xml:"w:bottom,omitempty"`
	Right   *TableCellSpace `xml:"w:right,omitempty"`
}

TableCellMargins 表格单元格边距

type TableCellMarginsCell

type TableCellMarginsCell struct {
	XMLName xml.Name            `xml:"w:tcMar"`
	Top     *TableCellSpaceCell `xml:"w:top,omitempty"`
	Left    *TableCellSpaceCell `xml:"w:left,omitempty"`
	Bottom  *TableCellSpaceCell `xml:"w:bottom,omitempty"`
	Right   *TableCellSpaceCell `xml:"w:right,omitempty"`
}

TableCellMarginsCell 单元格边距(与表格边距不同的XML结构)

type TableCellProperties

type TableCellProperties struct {
	XMLName       xml.Name              `xml:"w:tcPr"`
	TableCellW    *TableCellW           `xml:"w:tcW,omitempty"`
	VAlign        *VAlign               `xml:"w:vAlign,omitempty"`
	GridSpan      *GridSpan             `xml:"w:gridSpan,omitempty"`
	VMerge        *VMerge               `xml:"w:vMerge,omitempty"`
	TextDirection *TextDirection        `xml:"w:textDirection,omitempty"`
	Shd           *TableCellShading     `xml:"w:shd,omitempty"`       // 单元格背景
	TcBorders     *TableCellBorders     `xml:"w:tcBorders,omitempty"` // 单元格边框
	TcMar         *TableCellMarginsCell `xml:"w:tcMar,omitempty"`     // 单元格边距
	NoWrap        *NoWrap               `xml:"w:noWrap,omitempty"`    // 禁止换行
	HideMark      *HideMark             `xml:"w:hideMark,omitempty"`  // 隐藏标记
}

TableCellProperties 表格单元格属性

type TableCellShading

type TableCellShading struct {
	XMLName   xml.Name `xml:"w:shd"`
	Val       string   `xml:"w:val,attr"`                 // 底纹样式
	Color     string   `xml:"w:color,attr,omitempty"`     // 前景色
	Fill      string   `xml:"w:fill,attr,omitempty"`      // 背景色
	ThemeFill string   `xml:"w:themeFill,attr,omitempty"` // 主题填充色
}

TableCellShading 单元格背景

type TableCellSpace

type TableCellSpace struct {
	W    string `xml:"w:w,attr"`
	Type string `xml:"w:type,attr"`
}

TableCellSpace 表格单元格空间

type TableCellSpaceCell

type TableCellSpaceCell struct {
	W    string `xml:"w:w,attr"`
	Type string `xml:"w:type,attr"`
}

TableCellSpaceCell 单元格空间设置

type TableCellW

type TableCellW struct {
	XMLName xml.Name `xml:"w:tcW"`
	W       string   `xml:"w:w,attr"`
	Type    string   `xml:"w:type,attr"`
}

TableCellW 单元格宽度

type TableConfig

type TableConfig struct {
	Rows      int        // 行数
	Cols      int        // 列数
	Width     int        // 表格总宽度(磅)
	ColWidths []int      // 各列宽度(磅),如果为空则平均分配
	Data      [][]string // 初始数据
}

TableConfig 表格配置

type TableGrid

type TableGrid struct {
	XMLName xml.Name       `xml:"w:tblGrid"`
	Cols    []TableGridCol `xml:"w:gridCol"`
}

TableGrid 表格网格

type TableGridCol

type TableGridCol struct {
	XMLName xml.Name `xml:"w:gridCol"`
	W       string   `xml:"w:w,attr,omitempty"`
}

TableGridCol 表格网格列

type TableIndentation

type TableIndentation struct {
	XMLName xml.Name `xml:"w:tblInd"`
	W       string   `xml:"w:w,attr"`
	Type    string   `xml:"w:type,attr"`
}

TableIndentation 表格缩进

type TableJc

type TableJc struct {
	XMLName xml.Name `xml:"w:jc"`
	Val     string   `xml:"w:val,attr"`
}

TableJc 表格对齐

type TableLayoutConfig

type TableLayoutConfig struct {
	Alignment   TableAlignment    // 表格对齐方式
	TextWrap    TableTextWrap     // 文字环绕类型
	Position    TablePosition     // 定位类型
	Positioning *TablePositioning // 定位详细配置(仅在Position为Floating时有效)
}

TableLayoutConfig 表格布局配置

type TableLayoutType

type TableLayoutType struct {
	XMLName xml.Name `xml:"w:tblLayout"`
	Type    string   `xml:"w:type,attr"` // fixed, autofit
}

TableLayoutType 表格布局类型

type TableLook

type TableLook struct {
	XMLName  xml.Name `xml:"w:tblLook"`
	Val      string   `xml:"w:val,attr"`
	FirstRow string   `xml:"w:firstRow,attr,omitempty"`
	LastRow  string   `xml:"w:lastRow,attr,omitempty"`
	FirstCol string   `xml:"w:firstColumn,attr,omitempty"`
	LastCol  string   `xml:"w:lastColumn,attr,omitempty"`
	NoHBand  string   `xml:"w:noHBand,attr,omitempty"`
	NoVBand  string   `xml:"w:noVBand,attr,omitempty"`
}

TableLook 表格外观

type TablePageBreakConfig

type TablePageBreakConfig struct {
	KeepWithNext    bool // 与下一段落保持在一起
	KeepLines       bool // 保持行在一起
	PageBreakBefore bool // 段落前分页
	WidowControl    bool // 孤行控制
}

TablePageBreakConfig 表格分页配置

type TablePosition

type TablePosition string

TablePosition 表格定位类型

const (
	// PositionInline 行内定位(默认)
	PositionInline TablePosition = "inline"
	// PositionFloating 浮动定位
	PositionFloating TablePosition = "floating"
)

type TablePositioning

type TablePositioning struct {
	XMLName        xml.Name `xml:"w:tblpPr"`
	LeftFromText   string   `xml:"w:leftFromText,attr,omitempty"`   // 距离左侧文字的距离
	RightFromText  string   `xml:"w:rightFromText,attr,omitempty"`  // 距离右侧文字的距离
	TopFromText    string   `xml:"w:topFromText,attr,omitempty"`    // 距离上方文字的距离
	BottomFromText string   `xml:"w:bottomFromText,attr,omitempty"` // 距离下方文字的距离
	VertAnchor     string   `xml:"w:vertAnchor,attr,omitempty"`     // 垂直锚点
	HorzAnchor     string   `xml:"w:horzAnchor,attr,omitempty"`     // 水平锚点
	TblpXSpec      string   `xml:"w:tblpXSpec,attr,omitempty"`      // 水平对齐规格
	TblpYSpec      string   `xml:"w:tblpYSpec,attr,omitempty"`      // 垂直对齐规格
	TblpX          string   `xml:"w:tblpX,attr,omitempty"`          // X坐标
	TblpY          string   `xml:"w:tblpY,attr,omitempty"`          // Y坐标
}

TablePositioning 表格定位配置

type TableProperties

type TableProperties struct {
	XMLName      xml.Name          `xml:"w:tblPr"`
	TableW       *TableWidth       `xml:"w:tblW,omitempty"`
	TableJc      *TableJc          `xml:"w:jc,omitempty"`
	TableLook    *TableLook        `xml:"w:tblLook,omitempty"`
	TableStyle   *TableStyle       `xml:"w:tblStyle,omitempty"`   // 表格样式
	TableBorders *TableBorders     `xml:"w:tblBorders,omitempty"` // 表格边框
	Shd          *TableShading     `xml:"w:shd,omitempty"`        // 表格底纹/背景
	TableCellMar *TableCellMargins `xml:"w:tblCellMar,omitempty"` // 表格单元格边距
	TableLayout  *TableLayoutType  `xml:"w:tblLayout,omitempty"`  // 表格布局类型
	TableInd     *TableIndentation `xml:"w:tblInd,omitempty"`     // 表格缩进
}

TableProperties 表格属性

type TableRow

type TableRow struct {
	XMLName    xml.Name            `xml:"w:tr"`
	Properties *TableRowProperties `xml:"w:trPr,omitempty"`
	Cells      []TableCell         `xml:"w:tc"`
}

TableRow 表格行

type TableRowH

type TableRowH struct {
	XMLName xml.Name `xml:"w:trHeight"`
	Val     string   `xml:"w:val,attr,omitempty"`
	HRule   string   `xml:"w:hRule,attr,omitempty"`
}

TableRowH 表格行高

type TableRowProperties

type TableRowProperties struct {
	XMLName   xml.Name   `xml:"w:trPr"`
	TableRowH *TableRowH `xml:"w:trHeight,omitempty"`
	CantSplit *CantSplit `xml:"w:cantSplit,omitempty"` // 禁止跨页分割
	TblHeader *TblHeader `xml:"w:tblHeader,omitempty"` // 标题行重复
}

TableRowProperties 表格行属性

func (*TableRowProperties) SetCantSplit

func (trp *TableRowProperties) SetCantSplit(cantSplit bool)

扩展现有的TableRowProperties结构

func (*TableRowProperties) SetTblHeader

func (trp *TableRowProperties) SetTblHeader(isHeader bool)

type TableRowPropertiesExtended

type TableRowPropertiesExtended struct {
	XMLName   xml.Name   `xml:"w:trPr"`
	TableRowH *TableRowH `xml:"w:trHeight,omitempty"`
	CantSplit *CantSplit `xml:"w:cantSplit,omitempty"`
	TblHeader *TblHeader `xml:"w:tblHeader,omitempty"`
	KeepNext  *KeepNext  `xml:"w:keepNext,omitempty"`
	KeepLines *KeepLines `xml:"w:keepLines,omitempty"`
}

扩展TableRowProperties以支持分页控制

type TableShading

type TableShading struct {
	XMLName   xml.Name `xml:"w:shd"`
	Val       string   `xml:"w:val,attr"`                 // 底纹样式
	Color     string   `xml:"w:color,attr,omitempty"`     // 前景色
	Fill      string   `xml:"w:fill,attr,omitempty"`      // 背景色
	ThemeFill string   `xml:"w:themeFill,attr,omitempty"` // 主题填充色
}

TableShading 表格底纹/背景

type TableStyle

type TableStyle struct {
	XMLName xml.Name `xml:"w:tblStyle"`
	Val     string   `xml:"w:val,attr"`
}

TableStyle 表格样式引用

type TableStyleConfig

type TableStyleConfig struct {
	Template          TableStyleTemplate // 样式模板
	StyleID           string             // 自定义样式ID
	FirstRowHeader    bool               // 首行作为标题
	LastRowTotal      bool               // 最后一行作为总计
	FirstColumnHeader bool               // 首列作为标题
	LastColumnTotal   bool               // 最后一列作为总计
	BandedRows        bool               // 交替行颜色
	BandedColumns     bool               // 交替列颜色
}

TableStyleConfig 表格样式配置

type TableStyleTemplate

type TableStyleTemplate string

TableStyleTemplate 表格样式模板

const (
	TableStyleTemplateNormal    TableStyleTemplate = "TableNormal"    // 普通表格
	TableStyleTemplateGrid      TableStyleTemplate = "TableGrid"      // 网格表格
	TableStyleTemplateList      TableStyleTemplate = "TableList"      // 列表表格
	TableStyleTemplateColorful1 TableStyleTemplate = "TableColorful1" // 彩色表格1
	TableStyleTemplateColorful2 TableStyleTemplate = "TableColorful2" // 彩色表格2
	TableStyleTemplateColorful3 TableStyleTemplate = "TableColorful3" // 彩色表格3
	TableStyleTemplateColumns1  TableStyleTemplate = "TableColumns1"  // 列样式1
	TableStyleTemplateColumns2  TableStyleTemplate = "TableColumns2"  // 列样式2
	TableStyleTemplateColumns3  TableStyleTemplate = "TableColumns3"  // 列样式3
	TableStyleTemplateRows1     TableStyleTemplate = "TableRows1"     // 行样式1
	TableStyleTemplateRows2     TableStyleTemplate = "TableRows2"     // 行样式2
	TableStyleTemplateRows3     TableStyleTemplate = "TableRows3"     // 行样式3
	TableStyleTemplatePlain1    TableStyleTemplate = "TablePlain1"    // 简洁表格1
	TableStyleTemplatePlain2    TableStyleTemplate = "TablePlain2"    // 简洁表格2
	TableStyleTemplatePlain3    TableStyleTemplate = "TablePlain3"    // 简洁表格3
)

type TableTextWrap

type TableTextWrap string

TableTextWrap 表格文字环绕类型

const (
	// TextWrapNone 无环绕(默认)
	TextWrapNone TableTextWrap = "none"
	// TextWrapAround 环绕表格
	TextWrapAround TableTextWrap = "around"
)

type TableWidth

type TableWidth struct {
	XMLName xml.Name `xml:"w:tblW"`
	W       string   `xml:"w:w,attr"`
	Type    string   `xml:"w:type,attr"`
}

TableWidth 表格宽度

type Tabs

type Tabs struct {
	XMLName xml.Name `xml:"w:tabs"`
	Tabs    []TabDef `xml:"w:tab"`
}

Tabs 制表符设置

type TblHeader

type TblHeader struct {
	XMLName xml.Name `xml:"w:tblHeader"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

TblHeader 表格标题行

type Text

type Text struct {
	XMLName xml.Name `xml:"w:t"`
	Space   string   `xml:"xml:space,attr,omitempty"`
	Content string   `xml:",chardata"`
}

Text 文本内容

type TextDirection

type TextDirection struct {
	XMLName xml.Name `xml:"w:textDirection"`
	Val     string   `xml:"w:val,attr"`
}

TextDirection 文字方向

type TextFormat

type TextFormat struct {
	Bold      bool   // 是否粗体
	Italic    bool   // 是否斜体
	FontSize  int    // 字体大小(磅)
	FontColor string // 字体颜色(十六进制,如 "FF0000" 表示红色)
	FontName  string // 字体名称
}

TextFormat 文本格式配置

type TitlePage

type TitlePage struct {
	XMLName xml.Name `xml:"w:titlePg"`
}

TitlePage 首页不同设置

type VAlign

type VAlign struct {
	XMLName xml.Name `xml:"w:vAlign"`
	Val     string   `xml:"w:val,attr"`
}

VAlign 垂直对齐

type VMerge

type VMerge struct {
	XMLName xml.Name `xml:"w:vMerge"`
	Val     string   `xml:"w:val,attr,omitempty"`
}

VMerge 垂直合并(行合并)

type ValidationError

type ValidationError struct {
	Field   string // 字段名
	Value   string // 错误值
	Message string // 错误消息
}

ValidationError 验证错误

func NewValidationError

func NewValidationError(field, value, message string) *ValidationError

NewValidationError 创建新的验证错误

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error 实现error接口

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL