word

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2026 License: LGPL-3.0 Imports: 22 Imported by: 0

README

GoWord

English | 中文

Go Version Go Reference CI


English

Introduction

GoWord is a pure-Go library for creating, reading, and filling Microsoft Word documents. It writes native OpenXML Word2007 (.docx) packages and ports the core architecture of PHPWord / PHPOffice.

The public API keeps PHPWord names (AddSection, AddText, IOFactory, TemplateProcessor) while using idiomatic Go types and error returns.

Zero third-party dependencies: go.mod has no external require. OOXML is serialized with the standard library encoding/xml; .docx packages are packed and unpacked with archive/zip.

Features
  • Zero dependencies — Go standard library only (encoding/xml, archive/zip, image, …)
  • Word 2007 / OpenXML — generate and load .docx / .docm (WordprocessingML)
  • Paragraphs & rich text — AddText, TextRun, headings, breaks, hyperlinks, bookmarks
  • Tables — rows, cells, width, merge, borders, shading
  • Images — from file path or in-memory bytes
  • Headers & footers — default, first page, even page; watermarks
  • Formulas — Office Math (OMML) via pkg/math (fractions, superscripts, identifiers, operators)
  • Styles — font, paragraph, table, numbering, section, paper size and margins
  • Template fill — replace ${variable} placeholders, clone rows/blocks, insert images and charts
  • More — lists, charts, footnotes/endnotes, HTML import, document properties
Installation
go get github.com/yunkeweb/go-word@v0.1.0

Requires Go 1.21+.

Quick Start

Create a document, register paragraph styles, and save output.docx:

package main

import (
	"log"

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

func main() {
	doc := word.New()

	doc.AddFontStyle("rStyle", style.Font{
		Bold: true,
		Size: 16,
		Name: "Calibri",
	})
	doc.AddParagraphStyle("pStyle", style.Paragraph{
		Alignment: style.JcCenter,
		Spacing:   style.Spacing{After: 200},
	})
	doc.AddTitleStyle(1, style.Font{Bold: true, Size: 18}, style.Paragraph{
		Spacing: style.Spacing{After: 240},
	})

	section := doc.AddSection()
	section.AddTitle("Welcome to GoWord", 1)
	section.AddText("Hello, Word 2007.", "rStyle", "pStyle")
	section.AddText("This document was built with the Go standard library.")

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

A longer runnable sample lives in examples/simple. API docs: pkg.go.dev/github.com/yunkeweb/go-word.

License

GNU Lesser General Public License version 3, same family as PHPWord. See LICENSE.


中文

项目简介

GoWord 是纯 Go 实现的 Word 文档库,面向原生 OpenXML Word2007(.docx) 读写,移植自 PHPWord / PHPOffice 的核心架构与文档模型。

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

零第三方依赖: go.mod 不含任何外部 require。OpenXML 仅使用标准库 encoding/xml 序列化;.docx 仅使用 archive/zip 打包与解包。

核心特性
  • 零依赖 — 仅使用 Go 标准库(encoding/xml、archive/zip、image 等)
  • Word 2007 / OpenXML — 生成与加载 .docx / .docm(WordprocessingML)
  • 段落与富文本 — AddText、TextRun、标题、换行、超链接、书签
  • 表格 — 行、单元格、宽度、合并、边框、底纹
  • 图片 — 本地路径或内存字节
  • 页眉页脚 — 默认 / 首页 / 偶数页,以及水印
  • 公式 — 通过 pkg/math 写入 Office Math(OMML):分数、上下标、标识符与运算符
  • 样式配置 — 字体、段落、表格、编号、节、纸张与页边距
  • 模板变量 — 替换 ${variable} 占位符,支持行/块克隆、插入图片与图表
  • 更多 — 列表、图表、脚注/尾注、HTML 导入、文档属性
安装
go get github.com/yunkeweb/go-word@v0.1.0

需要 Go 1.21 或更高版本。

快速开始

新建文档、添加段落样式,并保存为 output.docx:

package main

import (
	"log"

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

func main() {
	doc := word.New()

	doc.AddFontStyle("rStyle", style.Font{
		Bold: true,
		Size: 16,
		Name: "Calibri",
	})
	doc.AddParagraphStyle("pStyle", style.Paragraph{
		Alignment: style.JcCenter,
		Spacing:   style.Spacing{After: 200},
	})
	doc.AddTitleStyle(1, style.Font{Bold: true, Size: 18}, style.Paragraph{
		Spacing: style.Spacing{After: 240},
	})

	section := doc.AddSection()
	section.AddTitle("Welcome to GoWord", 1)
	section.AddText("Hello, Word 2007.", "rStyle", "pStyle")
	section.AddText("This document was built with the Go standard library.")

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

更完整的可运行示例见 examples/simple。包文档:pkg.go.dev/github.com/yunkeweb/go-word。

开源协议

GNU Lesser General Public License version 3,与 PHPWord 同族。详见 LICENSE。

Documentation

Overview

Package word is a pure-Go port of PHPWord for creating, reading, and filling Microsoft Word documents.

The public API follows PHPWord naming (AddSection, AddText, IOFactory) while using idiomatic Go types and error returns. The library depends only on the Go standard library.

doc := word.New()
section := doc.AddSection()
section.AddText("Hello World")
if err := doc.Save("hello.docx"); err != nil {
    log.Fatal(err)
}

Index

Constants

View Source
const (
	UnitTwip  = "twip"
	UnitCM    = "cm"
	UnitMM    = "mm"
	UnitInch  = "inch"
	UnitPoint = "point"
	UnitPica  = "pica"
)

Variables

This section is empty.

Functions

func AddHTML

func AddHTML(dst htmlContainer, html string, fullHTML ...bool) error

AddHTML parses HTML and appends equivalent elements to dst (PHPWord Shared\Html::addHtml).

func DefaultAsianFontName

func DefaultAsianFontName() string

DefaultAsianFontName returns the process-wide default East-Asian font.

func DefaultFontColor

func DefaultFontColor() string

DefaultFontColor returns the process-wide default color (hex, no #).

func DefaultFontName

func DefaultFontName() string

DefaultFontName returns the process-wide default font.

func DefaultFontSize

func DefaultFontSize() float64

DefaultFontSize returns the process-wide default size in points.

func DefaultPaper

func DefaultPaper() string

DefaultPaper returns the process-wide default paper size name.

func ExtractVariables

func ExtractVariables(filename string, readerName ...string) ([]string, error)

ExtractVariables returns ${placeholder} names from a template file.

func HasCompatibility

func HasCompatibility() bool

HasCompatibility reports XMLWriter compatibility mode (PHP Settings::hasCompatibility).

func IsDefaultRtl

func IsDefaultRtl() *bool

IsDefaultRtl reports the process-wide default RTL flag.

func IsOutputEscapingEnabled

func IsOutputEscapingEnabled() bool

IsOutputEscapingEnabled reports whether XML escaping is on.

func MeasurementUnit

func MeasurementUnit() string

MeasurementUnit returns the process-wide unit (twip, cm, mm, inch, point, pica).

func SetCompatibility

func SetCompatibility(v bool)

SetCompatibility toggles XMLWriter compatibility mode.

func SetDefaultAsianFontName

func SetDefaultAsianFontName(name string)

SetDefaultAsianFontName sets the process-wide default East-Asian font.

func SetDefaultFontColor

func SetDefaultFontColor(color string)

SetDefaultFontColor sets the process-wide default color.

func SetDefaultFontName

func SetDefaultFontName(name string)

SetDefaultFontName sets the process-wide default font.

func SetDefaultFontSize

func SetDefaultFontSize(size float64)

SetDefaultFontSize sets the process-wide default size in points.

func SetDefaultPaper

func SetDefaultPaper(name string)

SetDefaultPaper sets the process-wide default paper size name.

func SetDefaultRtl

func SetDefaultRtl(v *bool)

SetDefaultRtl sets the process-wide default RTL flag.

func SetMacroChars

func SetMacroChars(open, close string)

SetMacroChars sets both placeholder delimiters.

func SetMacroClosingChars

func SetMacroClosingChars(s string)

SetMacroClosingChars sets the placeholder closing delimiter.

func SetMacroOpeningChars

func SetMacroOpeningChars(s string)

SetMacroOpeningChars sets the placeholder opening delimiter (PHPWord).

func SetMeasurementUnit

func SetMeasurementUnit(unit string)

SetMeasurementUnit sets the process-wide unit.

func SetOutputEscapingEnabled

func SetOutputEscapingEnabled(v bool)

SetOutputEscapingEnabled toggles XML escaping of text (always recommended).

func SetTempDir

func SetTempDir(dir string)

SetTempDir sets a user-defined temporary directory.

func SetZipClass

func SetZipClass(name string)

SetZipClass is accepted for PHP parity; Go always uses archive/zip.

func TempDir

func TempDir() string

TempDir returns the user-defined temporary directory.

func ZipClass

func ZipClass() string

ZipClass returns the zip backend name (always ZipArchive in Go).

Types

type Document

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

Document is the PHPWord PhpWord class: an in-memory word-processing document.

func Load

func Load(filename string, readerName ...string) (*Document, error)

Load loads a document (PHPWord IOFactory::load). If readerName is omitted, the format is inferred from the file extension.

func LoadBytes

func LoadBytes(data []byte) (*Document, error)

func New

func New() *Document

New creates an empty document (PHPWord constructor).

func (*Document) AddFontStyle

func (d *Document) AddFontStyle(name string, font any, para ...any)

AddFontStyle registers a named character style (PHPWord addFontStyle).

func (*Document) AddLinkStyle

func (d *Document) AddLinkStyle(name string, font any)

AddLinkStyle registers the Hyperlink character style.

func (*Document) AddNumberingStyle

func (d *Document) AddNumberingStyle(name string, num any)

AddNumberingStyle registers a named numbering definition.

func (*Document) AddParagraphStyle

func (d *Document) AddParagraphStyle(name string, para any)

AddParagraphStyle registers a named paragraph style.

func (*Document) AddSection

func (d *Document) AddSection(st ...any) *element.Section

AddSection appends a section (PHPWord addSection).

func (*Document) AddTableStyle

func (d *Document) AddTableStyle(name string, table any, firstRow ...any)

AddTableStyle registers a named table style.

func (*Document) AddTitleStyle

func (d *Document) AddTitleStyle(depth int, font any, para ...any)

AddTitleStyle registers HeadingN (depth 1-9). depth 0 is Title.

func (*Document) Bytes

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

Bytes returns the Word2007 package as a byte slice.

func (*Document) Compatibility

func (d *Document) Compatibility() *metadata.Compatibility

Compatibility returns OOXML compatibility settings.

func (*Document) CountStyles

func (d *Document) CountStyles() int

CountStyles returns the number of registered named styles.

func (*Document) DocInfo

func (d *Document) DocInfo() *metadata.DocInfo

DocInfo returns document properties.

func (*Document) GetBookmarks

func (d *Document) GetBookmarks() []*element.Bookmark

GetBookmarks returns bookmark elements.

func (*Document) GetCharts

func (d *Document) GetCharts() []*element.Chart

GetCharts returns chart elements.

func (*Document) GetComments

func (d *Document) GetComments() []*element.Comment

GetComments returns comment elements.

func (*Document) GetCompatibility

func (d *Document) GetCompatibility() *metadata.Compatibility

GetCompatibility is the PHPWord name for Compatibility.

func (*Document) GetDefaultAsianFontName

func (d *Document) GetDefaultAsianFontName() string

func (*Document) GetDefaultFontColor

func (d *Document) GetDefaultFontColor() string

func (*Document) GetDefaultFontName

func (d *Document) GetDefaultFontName() string

func (*Document) GetDefaultFontSize

func (d *Document) GetDefaultFontSize() float64

func (*Document) GetDocInfo

func (d *Document) GetDocInfo() *metadata.DocInfo

GetDocInfo is the PHPWord name for DocInfo.

func (*Document) GetEndnotes

func (d *Document) GetEndnotes() []*element.Endnote

GetEndnotes returns endnote elements.

func (*Document) GetFootnotes

func (d *Document) GetFootnotes() []*element.Footnote

GetFootnotes returns footnote elements.

func (*Document) GetSection

func (d *Document) GetSection(index int) *element.Section

GetSection returns the section at index, or nil.

func (*Document) GetSections

func (d *Document) GetSections() []*element.Section

GetSections is the PHPWord name for Sections.

func (*Document) GetSettings

func (d *Document) GetSettings() *metadata.Settings

GetSettings is the PHPWord name for Settings.

func (*Document) GetStyle

func (d *Document) GetStyle(name string) *NamedStyle

GetStyle returns a named style, or nil.

func (*Document) GetStyles

func (d *Document) GetStyles() []NamedStyle

GetStyles returns registered named styles (PHPWord Style::getStyles).

func (*Document) GetTitles

func (d *Document) GetTitles() []*element.Title

GetTitles returns heading elements in document order.

func (*Document) ResetStyles

func (d *Document) ResetStyles()

ResetStyles clears the named-style registry (PHPWord Style::resetStyles).

func (*Document) Save

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

Save writes the document as Word2007 (.docx).

func (*Document) SaveAs

func (d *Document) SaveAs(filename, format string) error

SaveAs writes the document in the named format.

func (*Document) Sections

func (d *Document) Sections() []*element.Section

Sections returns all sections.

func (*Document) SetDefaultAsianFontName

func (d *Document) SetDefaultAsianFontName(name string)

func (*Document) SetDefaultFontColor

func (d *Document) SetDefaultFontColor(color string)

func (*Document) SetDefaultFontName

func (d *Document) SetDefaultFontName(name string)

func (*Document) SetDefaultFontSize

func (d *Document) SetDefaultFontSize(size float64)

func (*Document) SetDefaultParagraphStyle

func (d *Document) SetDefaultParagraphStyle(para any)

SetDefaultParagraphStyle sets the Normal style.

func (*Document) Settings

func (d *Document) Settings() *metadata.Settings

Settings returns document settings.

func (*Document) SortSections

func (d *Document) SortSections(less func(a, b *element.Section) bool)

SortSections sorts sections with the given comparison.

func (*Document) WriteTo

func (d *Document) WriteTo(dest io.Writer) (int64, error)

WriteTo writes a Word2007 package to dest.

type NamedStyle

type NamedStyle struct {
	Name      string
	Kind      string
	Font      *style.Font
	Paragraph *style.Paragraph
	Table     *style.Table
	FirstRow  *style.Table
	Numbering *style.Numbering
	Depth     int
}

NamedStyle is a document-scoped style definition (PHPWord Style registry entry).

type PhpWord

type PhpWord = Document

PhpWord is an alias for Document, matching the PHP class name.

type Reader

type Reader interface {
	Load(filename string) (*Document, error)
}

Reader loads a document from a file.

func CreateReader

func CreateReader(name string) (Reader, error)

CreateReader returns a reader for the named format (PHPWord IOFactory::createReader).

type TemplateProcessor

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

TemplateProcessor fills ${placeholders} in an existing .docx (PHPWord TemplateProcessor).

func NewTemplateProcessor

func NewTemplateProcessor(filename string) (*TemplateProcessor, error)

NewTemplateProcessor opens a .docx template from disk.

func NewTemplateProcessorBytes

func NewTemplateProcessorBytes(data []byte) (*TemplateProcessor, error)

NewTemplateProcessorBytes opens a .docx template from memory.

func (*TemplateProcessor) Bytes

func (t *TemplateProcessor) Bytes() ([]byte, error)

Bytes returns the filled template as a .docx package.

func (*TemplateProcessor) CloneBlock

func (t *TemplateProcessor) CloneBlock(blockName string, count int) error

CloneBlock clones the region between ${block} and ${/block} count times.

func (*TemplateProcessor) CloneBlockAndSetValues

func (t *TemplateProcessor) CloneBlockAndSetValues(blockName string, values []map[string]string) error

CloneBlockAndSetValues clones ${block}...${/block} once per values row (PHPWord).

func (*TemplateProcessor) CloneRow

func (t *TemplateProcessor) CloneRow(search string, count int) error

CloneRow clones the table row that contains ${search} count times, renaming macros to ${search#1}, ${search#2}, ...

func (*TemplateProcessor) CloneRowAndSetValues

func (t *TemplateProcessor) CloneRowAndSetValues(search string, values []map[string]string) error

CloneRowAndSetValues clones a row and fills ${name#n} from values.

func (*TemplateProcessor) DeleteBlock

func (t *TemplateProcessor) DeleteBlock(blockName string) error

DeleteBlock removes the region between ${block} and ${/block}.

func (*TemplateProcessor) DeleteRow

func (t *TemplateProcessor) DeleteRow(search string) error

DeleteRow removes the table row that contains ${search}.

func (*TemplateProcessor) GetVariableCount

func (t *TemplateProcessor) GetVariableCount() map[string]int

GetVariableCount returns placeholder name → occurrence count (PHPWord getVariableCount).

func (*TemplateProcessor) GetVariables

func (t *TemplateProcessor) GetVariables() []string

GetVariables returns unique placeholder names in first-seen order.

func (*TemplateProcessor) ReplaceBlock

func (t *TemplateProcessor) ReplaceBlock(blockName, replacement string) error

ReplaceBlock replaces the region between ${block} and ${/block}.

func (*TemplateProcessor) ReplaceCarriageReturns

func (t *TemplateProcessor) ReplaceCarriageReturns(s string) string

ReplaceCarriageReturns turns newlines into Word break runs (PHPWord).

func (*TemplateProcessor) ReplaceXmlBlock

func (t *TemplateProcessor) ReplaceXmlBlock(macroName, block, blockType string) error

ReplaceXmlBlock replaces the XML element of blockType that contains ${macro}.

func (*TemplateProcessor) Save

func (t *TemplateProcessor) Save(filename string) error

Save writes the filled template to filename.

func (*TemplateProcessor) SaveAs

func (t *TemplateProcessor) SaveAs(filename string) error

SaveAs is an alias for Save (PHPWord).

func (*TemplateProcessor) SetChart

func (t *TemplateProcessor) SetChart(search string, ch *element.Chart) error

SetChart replaces ${search} with a chart drawing and chart XML part (PHPWord).

func (*TemplateProcessor) SetCheckbox

func (t *TemplateProcessor) SetCheckbox(search string, checked bool)

SetCheckbox toggles a content-control checkbox at ${search}.

func (*TemplateProcessor) SetComplexBlock

func (t *TemplateProcessor) SetComplexBlock(search string, el element.Element) error

SetComplexBlock replaces the w:p containing ${search} with the rendered element.

func (*TemplateProcessor) SetComplexValue

func (t *TemplateProcessor) SetComplexValue(search string, el element.Element) error

SetComplexValue replaces the w:r containing ${search} with the rendered element.

func (*TemplateProcessor) SetImageValue

func (t *TemplateProcessor) SetImageValue(search, path string) error

SetImageValue replaces a placeholder with a drawing that references a new image part.

func (*TemplateProcessor) SetImageValueBytes

func (t *TemplateProcessor) SetImageValueBytes(search, filename string, data []byte) error

SetImageValueBytes embeds image bytes at ${search}.

func (*TemplateProcessor) SetMacroChars

func (t *TemplateProcessor) SetMacroChars(open, close string)

func (*TemplateProcessor) SetMacroClosingChars

func (t *TemplateProcessor) SetMacroClosingChars(s string)

func (*TemplateProcessor) SetMacroOpeningChars

func (t *TemplateProcessor) SetMacroOpeningChars(s string)

func (*TemplateProcessor) SetUpdateFields

func (t *TemplateProcessor) SetUpdateFields(update bool)

SetUpdateFields sets w:updateFields in word/settings.xml.

func (*TemplateProcessor) SetValue

func (t *TemplateProcessor) SetValue(search, replace string)

SetValue replaces ${search} with replace across document parts.

func (*TemplateProcessor) SetValueLimit

func (t *TemplateProcessor) SetValueLimit(search, replace string, limit int)

SetValueLimit replaces at most limit occurrences (-1 = all).

func (*TemplateProcessor) SetValues

func (t *TemplateProcessor) SetValues(values map[string]string)

SetValues replaces many placeholders.

type Writer

type Writer interface {
	Save(filename string) error
	WriteTo(w io.Writer) (int64, error)
}

Writer writes a document to a file or stream.

func CreateWriter

func CreateWriter(doc *Document, name string) (Writer, error)

CreateWriter returns a writer for the named format (PHPWord IOFactory::createWriter).

Directories

Path Synopsis
examples
simple command
pkg

Jump to

Keyboard shortcuts

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