• golang 读写 xlsx 文件


    利用 excelize 工具包即可完成 xlsx 文件的读写,示例代码如下。

    写 xlsx

    import (
    	"fmt"
    	"github.com/360EntSecGroup-Skylar/excelize"
    	"github.com/smartystreets/goconvey/convey"
    	"strconv"
    	"testing"
    )
    func TestGolangExcel(t *testing.T) {
    	convey.Convey("TestGolangExcel", t, func() {
    		// 打开一个xlsx文件
    		f, _ := excelize.OpenFile("book.xlsx")
    		index := f.GetActiveSheetIndex() // 获得默认工作簿的索引
    		// 创建一个新的工作簿,如果Sheet工作簿已存在则不需要这行
    		//index := f.NewSheet("Sheet1")
    		// 设置单元格的值
    		f.SetCellValue("Sheet1", "A1", "计划ID")
    
    		for i := 1; i <= 1000; i++ {
    			// A2~A1001这1000个单元格都填充写入"你好"
    			f.SetCellValue("Sheet1", "A" + strconv.Itoa(i+1), "你好")
    			// 每循环10次保存一次,这样不至于因为循环中某次失败导致所有数据都丢失
    			if i % 10 == 0 {
    				if err := f.SaveAs("book.xlsx"); err != nil {
    					fmt.println(err.Error())
    				}
    			}
    		}
    		// 设置工作簿的默认工作表
    		f.SetActiveSheet(index)
    		// 根据指定路径保存文件
    		if err := f.SaveAs("book.xlsx"); err != nil {
    			fmt.println(err.Error())
    		}
    	})
    }
    

    读 xlsx

    package main
     
    import (
        "fmt"
     
        "github.com/360EntSecGroup-Skylar/excelize"
    )
     
    func main() {
        f, err := excelize.OpenFile("Book1.xlsx")
        if err != nil {
            fmt.Println(err)
            return
        }
        // Get value from cell by given worksheet name and axis.
        cell, err := f.GetCellValue("Sheet1", "B2")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(cell)
        // Get all the rows in the Sheet1.
        rows, err := f.GetRows("Sheet1")
        for _, row := range rows {
            for _, colCell := range row {
                fmt.Print(colCell, "\t")
            }
            fmt.Println()
        }
    }
    

    参考GO读写excel

  • 相关阅读:
    HDU 2460 Network 傻逼Tarjan
    HTTP状态码
    Spring Tool Suite(STS)安装
    Manajro17配置
    VsCode搭建Java开发环境
    《从零开始搭建游戏服务器》项目管理工具Maven
    Debian9安装MariaDB
    Intellij从无到有创建项目
    PostgreSQL 二进制安装
    Intellij IDEA创建项目
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/16192410.html
Copyright © 2020-2023  润新知