Skip to content

快速开始 ​

本页生成一份 .docx,覆盖多数团队第一天就会用到的四项能力:原生 Office Math 公式、DrawingML 形状、双栏节,以及 Save。

公开 API 沿用 PHPWord 命名(AddSection、AddText、IOFactory),并使用惯用的 Go 类型与 error 返回。

New / AddSection / Save ​

签名 ​

go
func New() *Document
func (d *Document) AddSection(style ...any) *element.Section
func (d *Document) Save(filename string) error

参数 ​

名称类型说明
style...any可选 style.Section(纸张、边距、方向、分节符)。
filenamestring目标路径。父目录必须已存在。

注意 ​

  • New 创建空文档,默认 run 字体为 Calibri 11 pt。
  • AddSection 追加一块 w:sectPr。正文元素挂在返回的 *element.Section 上。
  • Save 等价于 CreateWriter(doc, "Word2007") 再写文件。关系 ID(rIdN)与媒体名(word/media/imageN)在写出时分配。

完整示例 ​

保存为 main.go 后执行 go run .。Microsoft Word 打开 hello.docx 时不会弹出修复对话框。

go
package main

import (
	"log"

	"github.com/yunkeweb/go-word"
	"github.com/yunkeweb/go-word/style"
)

func main() {
	doc := word.New()
	doc.SetDefaultFontName("Calibri")
	doc.SetDefaultAsianFontName("Microsoft YaHei")
	doc.SetDefaultFontSize(11)

	info := doc.GetDocInfo()
	info.Title = "GoWord v0.13.0"
	info.Creator = "GoWord"

	sec := doc.AddSection()
	sec.AddTitle("GoWord v0.13.0", 1)
	sec.AddText("Native Office Math:")
	sec.AddMath(`\frac{a}{b}`)

	p := sec.AddTextRun()
	p.AddText("Pythagoras: ")
	p.AddMath(`x^{2} + y^{2} = z^{2}`)

	doc.AddShape(word.ShapeRoundRect, word.ShapeOptions{
		FillColor: "5B9BD5",
		LineColor: "2E75B6",
		Text:      "DrawingML",
		Font:      style.Font{Bold: true, Color: "FFFFFF"},
	})

	cols := doc.AddSection()
	cols.SetColumns(2, 720, true)
	cols.AddText("The left column starts here. Word flows this section into two equal columns.")
	cols.AddText("A separator line is emitted as w:cols w:sep.")

	if err := doc.Save("hello.docx"); err != nil {
		log.Fatal(err)
	}
}

Word 中的效果 ​

功能屏幕上OpenXML
展示公式可双击的居中公式w:p / m:oMathPara / m:oMath / m:f
行内公式勾股定理与标签同一行与 w:r 并列的 m:oMath
圆角矩形蓝色胶囊,白色 “DrawingML”wps:wsp / a:prstGeom prst="roundRect"
两栏等宽栏 + 竖向分隔线w:cols w:num="2" w:space="720" w:sep="1"

IOFactory 别名 ​

签名 ​

go
func CreateWriter(doc *Document, name string) (Writer, error)
func CreateReader(name string) (Reader, error)
func Load(filename string, readerName ...string) (*Document, error)
func Open(filePath string) (*Document, error)
func LoadWithOptions(filename string, opts ReadOptions) (*Document, error)
func OpenWithOptions(filePath string, opts ReadOptions) (*Document, error)
func ReadWithOptions(r io.Reader, opts ReadOptions) (*Document, error)
func LoadBytesWithOptions(data []byte, opts ReadOptions) (*Document, error)

name 为 "Word2007"(默认)。Load / Open 构建完整 DOM;O(1) 抽文本见 流式解析器。

处理不可信 ZIP 时使用 WithOptions 入口。ReadOptions 可限制压缩包大小、 单个解压部件大小、声明的解压总量以及条目数。字段为 0 表示关闭限制,负数会在 执行 I/O 前拒绝;超限返回 ErrReadLimitExceeded。

MaxArchiveSize 与 MaxPartSize 的单位是字节;MaxTotalSize 是 ZIP 部件声明的 解压大小总和;MaxEntries 统计 ZIP 条目数。选项只对当前调用生效,不改变旧的 无限制函数。读取模板时使用对应构造函数:

go
func NewTemplateProcessorWithOptions(filename string, opts ReadOptions) (*TemplateProcessor, error)
func NewTemplateProcessorBytesWithOptions(data []byte, opts ReadOptions) (*TemplateProcessor, error)

下一步 ​

主题页面
ZIP 如何组装架构设计
段落、表格、图片段落与 Run
SDT 表单控件结构化文档标签
跨页表头 / cantSplit表格
平铺水印与 AllowEdit水印与保护
LaTeX → Word 公式Office Math
图表DrawingML 图表

基于 GNU LGPL v3.0 发布。