1. 产品
  2.   字处理
  3.   GO
  4.   Go-Docx
 
  

通过免费 Go 库生成和解析 .docx 文件

开源 Go 文字处理库,可以编程方式读取和写入 Microsoft Word。向 DOCX 文件插入媒体文件、图像、文本、页眉/页脚和表格。

Go-Docx 库是什么?

在 Golang 开发领域,处理 Microsoft Word 文档(.docx)历来是一大挑战。许多现有库要么仅限于“只写”功能,要么附带昂贵的商业费用。Go-Docx(由 fumiama 维护)弥补了这一空白,作为最具功能性的开源库之一,旨在读取和写入 ECMA-376 Office Open XML 文件。它之所以有用,是因为它提供了一个高级 API,抽象了 Word 文件底层复杂的 XML 结构。

使 Go-Docx 脱颖而出的是其全面的功能集:文本格式化(颜色、大小、对齐)、图片插入、表格操作、形状、画布和分组。无论是生成发票、解析简历,还是自动化报告生成,该库都能在不调用外部应用的情况下处理复杂的 Office Open XML(ECMA-376)结构。它是一个由社区驱动的分支,已显著进化于其前身。不同于需要付费才能获取完整功能的商业替代品如 UniOffice,Go-Docx 在 AGPL-3.0 许可证下完全免费。

Previous Next

开始使用 Go-Docx

将 Go-Docx 引入项目的推荐方式是使用 GitHub。请使用以下命令进行顺畅的安装。

通过 GitHub 安装 Go-Docx

go get -d github.com/fumiama/go-docx@latest 

使用 Go 进行高级文档生成

Go-Docx 允许你使用结构化方法从头创建复杂文档。它负责初始化文档环境,包括默认主题和样式,确保生成的文件与 Microsoft Word 以及其他现代处理器完全兼容。以下是一个简单示例,演示如何在 Go 应用中生成 Word Docx 文件。

如何通过 Go 库生成 Word Docx 文件?

package main
import (
	"os"
	"github.com/fumiama/go-docx"
)

func main() {
	// Initialize a new document with a default theme
	w := docx.New().WithDefaultTheme()
	
	// Add a paragraph and basic text
	para := w.AddParagraph()
	para.AddText("Hello, this is a generated document!")

	// Save to local file
	f, _ := os.Create("simple.docx")
	w.WriteTo(f)
	f.Close()
}

通过 Go API 进行全面的文档解析

与许多竞争者不同,开源的 Go-Docx 库在读取现有文件方面表现出色。它可以解析 .docx 文件并遍历其正文项,如段落和表格。这使其成为数据提取或文档审计任务的理想选择,你需要以编程方式分析内容。以下示例展示了软件开发者如何在自己的 Go 应用中解析 Word 文档。

如何通过 Go 库解析 Word Docx 文档?

package main
import (
	"fmt"
	"os"
	"github.com/fumiama/go-docx"
)

func main() {
	readFile, _ := os.Open("existing.docx")
	info, _ := readFile.Stat()
	
	// Parse the file using its reader and size
	doc, _ := docx.Parse(readFile, info.Size())
	
	for _, item := range doc.Document.Body.Items {
		if p, ok := item.(*docx.Paragraph); ok {
			fmt.Println("Paragraph found:", p)
		}
	}
}

通过 Go 在 Docx 文件中动态构建表格

Open source Go-Docx library has included support for the creation and manipulation of tables, including nested tables—a feature often missing in simpler libraries. You can define rows, cells, and specific border styles, making it highly effective for generating financial reports, invoices, or data-heavy technical documentation. Here is a very useful code example that shows how to create a table inside Word documents via Go commands.

如何通过 Go 库在 Word 文件中创建简单表格?

func createTable(w *docx.Docx) {
	table := w.AddTable(2, 2) // Create a 2x2 table
	row := table.Rows[0]
	cell := row.Cells[0]
	
	p := cell.AddParagraph()
	p.AddText("Cell Content")
	
	// You can also adjust table properties here
}

丰富的文本样式和格式化支持

对排版的细粒度控制是此开源 Go 库的核心优势。你可以通过 Go-Docx 修改文本颜色、字体大小、对齐方式,甚至添加超链接或制表位。这使开发者能够生成专业且符合特定设计需求的品牌文档,而无需人工干预。

如何通过 Go 库对 Word 文档应用文本样式和格式化?

func styleText(w *docx.Docx) {
	para := w.AddParagraph()
	// Chain styling methods for concise code
	para.AddText("Important Header").Size("32").Color("FF0000")
	para.AddText("Subtext").Italic().Bold()
	
	// Add a link
	para.AddLink("Visit Website", "https://example.com")
}
 中国人