forked from pibigstar/go-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword.go
59 lines (50 loc) · 1.07 KB
/
word.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package word
import (
"github.com/nguyenthenguyen/docx"
"github.com/unidoc/unioffice/document"
)
// https://github.com/nguyenthenguyen/docx
func ReplaceWord(file string) error {
r, err := docx.ReadDocxFile(file)
if err != nil {
return err
}
docx := r.Editable()
docx.Replace("{name}", "派大星", -1)
docx.Replace("{age}", "20", -1)
docx.WriteToFile("new.docx")
r.Close()
return nil
}
// https://github.com/unidoc/unioffice
func ReplaceWithStyle(file string) error {
doc, err := document.Open(file)
if err != nil {
return err
}
paragraphs := []document.Paragraph{}
for _, p := range doc.Paragraphs() {
paragraphs = append(paragraphs, p)
}
for _, sdt := range doc.StructuredDocumentTags() {
for _, p := range sdt.Paragraphs() {
paragraphs = append(paragraphs, p)
}
}
for _, p := range paragraphs {
for _, r := range p.Runs() {
switch r.Text() {
case "{name}":
r.ClearContent()
r.AddText("派大星")
case "{age}":
r.ClearContent()
r.AddText("20")
default:
continue
}
}
}
doc.SaveToFile("new.docx")
return nil
}