英文:
How to use golang for .docx template (table content)
问题
如何使用golang处理.docx模板(表格内容):
英文:
How to use golang for .docx template (table content):
答案1
得分: 4
你可以使用这个简单的包:"github.com/lukasjarosch/go-docx"
。该包可以帮助你通过替换{variables}
中的文本内容来填充docx文件模板。
填充模板的代码如下:
package main
import (
"fmt"
docx "github.com/lukasjarosch/go-docx"
)
func main() {
replaceMap := docx.PlaceholderMap{
"_contract_name_": "Home rental",
"_name_": "John Doe",
"_summary_": "Terms and conditions",
"_date_": "13-04-2022",
"_condition_1_": "apartment should always be cleaned",
"_condition_2_": "term 2 ...",
"_condition_4_": "term 4 ...",
"_condition_3_": "term 3 ...",
"_condition_5_": "term 5 ...",
}
for i := 1; i <= 5; i++ {
replaceMap[fmt.Sprintf("_accept_%d", i)] = "✔️"
replaceMap[fmt.Sprintf("_reject_%d", i)] = ""
}
// 读取和解析模板docx文件
doc, err := docx.Open("template.docx")
if err != nil {
panic(err)
}
// 使用replaceMap中的值替换键
err = doc.ReplaceAll(replaceMap)
if err != nil {
panic(err)
}
// 写入一个新文件
err = doc.WriteToFile("replaced.docx")
if err != nil {
panic(err)
}
}
附注:该包不提供插入图片的功能。如果你想要插入图片,可以使用这个商业包:"github.com/unidoc/unioffice/document"
英文:
You can use this simple package: "github.com/lukasjarosch/go-docx"
. This package helps you fill docx file templates by replacing {variables}
with given text context.
Code to fill the template:
package main
import (
"fmt"
docx "github.com/lukasjarosch/go-docx"
)
func main() {
replaceMap := docx.PlaceholderMap{
"_contract_name_": "Home rental",
"_name_": "John Doe",
"_summary_": "Terms and conditions",
"_date_": "13-04-2022",
"_condition_1_": "apartment should always be cleaned",
"_condition_2_": "term 2 ...",
"_condition_4_": "term 4 ...",
"_condition_3_": "term 3 ...",
"_condition_5_": "term 5 ...",
}
for i := 1; i <= 5; i++ {
replaceMap[fmt.Sprintf("_accept_%d", i)] = "✔️"
replaceMap[fmt.Sprintf("_reject_%d", i)] = ""
}
// read and parse the template docx
doc, err := docx.Open("template.docx")
if err != nil {
panic(err)
}
// replace the keys with values from replaceMap
err = doc.ReplaceAll(replaceMap)
if err != nil {
panic(err)
}
// write out a new file
err = doc.WriteToFile("replaced.docx")
if err != nil {
panic(err)
}
}
P.S: this package does not provide functionality to insert images. If you want to insert images you can use this commercial package: "github.com/unidoc/unioffice/document"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论