golang 操作excel修改图片名称

安装插件

go get github.com/xuri/excelize/v2

示例代码

package main

import (
	"fmt"
	"os"
	"path"

	"github.com/xuri/excelize/v2"
)

func checkErr(err error, isReturn bool) {
	if err != nil {
		fmt.Println(err.Error())
		if isReturn {
			return
		}
	}
}

func main() {
	var image1 string
	var image2 string
	var classNum string
	f, err := excelize.OpenFile(os.Args[1])
	checkErr(err, true)
	defer func() {
		// Close the spreadsheet.
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	rows, err := f.GetRows("Sheet1")
	checkErr(err, true)
	for _, row := range rows {
		classNum = row[2]
		image1 = row[4]
		image1Ext := path.Ext(image1)
		if len(row) == 6 {
			image2 = row[5]
			image2Ext := path.Ext(image2)
			newFileName := classNum + "_2" + image2Ext
			os.Rename(image2, newFileName)
		}
		newFileName := classNum + "_1" + image1Ext
		os.Rename(image1, newFileName)
	}
}
posted @ 2022-04-22 16:24  昌慶  阅读(65)  评论(0编辑  收藏  举报