跳至主要內容

【Unioffice】一个操作Office的工具包

程序员李某某原创Goofficewordpptexcel小于 1 分钟

【Unioffice】一个操作Office的工具包

背景

学习这个包是因为想读取儿子英语老师 PPT 中的文本内容,根据所学自动生成相应练习题

安装

go get github.com/unidoc/unioffice

申请api-keyopen in new window

  • 注册
  • api keys 菜单中,添加一个 add api key

注意

只出现一次,记得复制保存

PPT

读取PPT

本地文件

package main

import (
	"fmt"
	"github.com/unidoc/unioffice/common/license"
	"github.com/unidoc/unioffice/presentation"
)

func init() {
	// Make sure to load your metered License API key prior to using the library.
	// If you need a key, you can sign up and create a free one at https://cloud.unidoc.io
	err := license.SetMeteredKey(`你的api key`)
	if err != nil {
		panic(err)
	}
}

func main() {
	// 打开一个 ppt 文件
	ppt, _ := presentation.Open("D:\\Users\\ext.liyuanhao3\\Desktop\\use.pptx")
	defer func(ppt *presentation.Presentation) {
		err := ppt.Close()
		if err != nil {
			panic(err)
		}
	}(ppt)

    // Slides拿到页数组
	for _, slide := range ppt.Slides() {
        // ExtractText 提取文本
		text := slide.ExtractText()
        // Text 转为string类型
		fmt.Println(text.Text())
	}
}

集成gin

func AnalysisPPT(c *gin.Context) {

	file, _ := c.FormFile("file")

	f, _ := file.Open()
	defer f.Close()
	size := file.Size

	// 读取文件内容
	data, _ := io.ReadAll(f)
	// 将文件内容转换为 io.ReaderAt
	reader := bytes.NewReader(data)

	ppt, _ := presentation.Read(reader, size)

	// ...
}
上次编辑于:
贡献者: ext.liyuanhao3