如何在Golang中追加docx文件

huangapple go评论100阅读模式
英文:

How to append docx file in Golang

问题

我想复制一个docx文件的所有内容(包括粗体、下划线、项目符号、段落等格式),并将其追加到另一个docx文件中。

在这种情况下,我想从Source/D1.docx复制内容,并将其追加到temp.docx中。

package main

import (
	"io/ioutil"
	"log"
	"os"
)

func main() {
	data, err := ioutil.ReadFile("./Source/D1.docx")
	if err != nil {
		log.Println(err)
	}

	file, err := os.OpenFile("temp.docx", os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Println(err)
	}
	file.Write(data)
}
英文:

I want to copy all the contents of a docx file (including its formatting like bold, underline, bullets, paragraphs, etc.) and append it to another docx file.

In this case I want to copy contents from Source/D1.docx and append it to temp.docx

package main

import (
	"io/ioutil"
	"log"
	"os"
)

func main() {
	data, err := ioutil.ReadFile("./Source/D1.docx")
	if err != nil {
		log.Println(err)
	}

	file, err := os.OpenFile("temp.docx", os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Println(err)
	}
	file.Write(data)
}

答案1

得分: 0

请执行以下操作:

git clone --depth 1 git://github.com/unidoc/unioffice
New-Item -ItemType Directory unioffice/document/merge
Set-Location unioffice/document/merge
git pull origin pull/448/head

然后在merge文件夹中创建以下文件:

package main

import (
   "github.com/unidoc/unioffice/document"
   "os"
   "path/filepath"
)

func main() {
   s := "TestDocument.docx"
   doc0, e := document.Open(s)
   if e != nil {
      panic(e)
   }
   defer doc0.Close()
   doc1, e := document.Open(s)
   if e != nil {
      panic(e)
   }
   defer doc1.Close()
   doc0.AddParagraph().AddRun().AddPageBreak()
   if e := doc0.Append(doc1); e != nil {
      panic(e)
   }
   out := filepath.Join(os.TempDir(), "merged.docx")
   doc0.SaveToFile(out)
}

请注意,这只是用于测试,如果要使用真实代码,您需要获取许可证。

https://github.com/unidoc/unioffice

英文:

Do this:

git clone --depth 1 git://github.com/unidoc/unioffice
New-Item -ItemType Directory unioffice/document/merge
Set-Location unioffice/document/merge
git pull origin pull/448/head

Then in the merge folder, make this file:

package main

import (
   "github.com/unidoc/unioffice/document"
   "os"
   "path/filepath"
)

func main() {
   s := "TestDocument.docx"
   doc0, e := document.Open(s)
   if e != nil {
      panic(e)
   }
   defer doc0.Close()
   doc1, e := document.Open(s)
   if e != nil {
      panic(e)
   }
   defer doc1.Close()
   doc0.AddParagraph().AddRun().AddPageBreak()
   if e := doc0.Append(doc1); e != nil {
      panic(e)
   }
   out := filepath.Join(os.TempDir(), "merged.docx")
   doc0.SaveToFile(out)
}

Note this is just for testing, for real code you will want to get a license.

https://github.com/unidoc/unioffice

huangapple
  • 本文由 发表于 2021年5月26日 22:55:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/67707482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定