当前位置: 首页 > 工具软件 > Go XSLX > 使用案例 >

go 读取xsl并写入xlsx

卫增
2023-12-01
package main

import (
	"fmt"
	"github.com/extrame/xls"
	"github.com/tealeg/xlsx"
	"log"
	"os"
	"strconv"
)

var xlsTitle = []string{"商品编码", "商品库存", "状态", "说明"}

type Goods struct {
	GoodsNo  string `json:"goods_no"`
	StockNum int    `json:"stock_num"`
}

func main() {
	pathFile := "./test.xls"
	xlsFiile, err := xls.Open(pathFile, "utf-8")
	if err != nil {
		panic(err)
	}
	var goods []Goods
	sheet1 := xlsFiile.GetSheet(0)
	if sheet1 != nil {
		fmt.Println(sheet1.MaxRow, sheet1.Name)
		for i := 1; i <= int(sheet1.MaxRow); i++ {
			if sheet1.Row(i) == nil {
				continue
			}
			row := sheet1.Row(i)
			var good Goods
			for index := row.FirstCol(); index < row.LastCol(); index++ {
				if index == 1 {
					good.GoodsNo = row.Col(index)
				}
				if index == 2 {
					good.StockNum, _ = strconv.Atoi(row.Col(index))
				}
			}
			goods = append(goods, good)
		}
	}
	xlsxFile := getXlsxFile("./test.xlsx")
	xlsxSheet := xlsxFile.Sheets[0]
	for _, good := range goods {
		var dataInsert = []string{}
		dataInsert = append(dataInsert, good.GoodsNo)
		dataInsert = append(dataInsert, strconv.Itoa(good.StockNum))
		dataInsert = append(dataInsert, "成功")
		dataInsert = append(dataInsert, "")
		insertRow(xlsxSheet, &dataInsert)
	}
	err = xlsxFile.Save("./test.xlsx")
	if err != nil {
		panic(err)
	}
}
func getXlsxFile(filename string) *xlsx.File {
	var file *xlsx.File
	if _, err := os.Stat(filename); err == nil {
		file, err = xlsx.OpenFile(filename)
		if err != nil {
			log.Fatal("open file----", err)
		}
	} else {
		file = xlsx.NewFile()
		sheet, err := file.AddSheet("sheet1")
		if err != nil {
			log.Fatal("new file", err)
		}
		insertRow(sheet, &xlsTitle)
	}
	return file
}
func insertRow(sheet *xlsx.Sheet, rowDataPtr *[]string) {
	row := sheet.AddRow()
	rowData := *rowDataPtr
	for _, v := range rowData {
		cell := row.AddCell()
		cell.Value = v
	}
}

 类似资料: