最近工作忙于作图,图表,经常和Excel打交道,这不要读写excel文件。以前都是用python,现在学习Go语言,刚好试试。

要操作excel,自然需要找读写Excel的Package,前人栽好树,等我去乘凉。

去哪里找合适的Package呢?

Go语言的包在 https://pkg.go.dev/。打开就能搜索。这里录入关键字xlsx(如果需要读写xls则录入xls也可以)。




Go语言将数据写入excel go语言操作excel_Go语言将数据写入excel

通过关键字找到需要的包



这里我们使用 github.com/tealeg/xlsx/v3




Go语言将数据写入excel go语言操作excel_字符串_02

xlsx 的v3版本



先点击Doc,看下文档。




Go语言将数据写入excel go语言操作excel_Go语言将数据写入excel_03

Document 文档全面解释了包



func FileToSlice ¶

func FileToSlice(path string, options ...FileOption) ([][][]string, error)

A convenient wrapper around File.ToSlice, FileToSlice will return the raw data contained in an Excel XLSX file as three dimensional slice. The first index represents the sheet number, the second the row number, and the third the cell number.

这个函数可以直接打开一个表格文件,读取到一个3维切片中,第一维是sheet表,第二维是行,第三维是列。非常简单方便。

其实我比较讨厌这种包装,因为打开文件之后,何时关闭不受我控制。




Go语言将数据写入excel go语言操作excel_字符串_04

这个错误就是表格文件打开后没有关闭,再次打开导致异常



For example:

var mySlice [][][]stringvar value stringmySlice = xlsx.FileToSlice("myXLSX.xlsx")value = mySlice[0][0][0]   //这就是 A1 了,简单吧value = mySlice[0][0][1]   //这就是 A1 了,简单吧

Here, value would be set to the raw value of the cell A1 in the first sheet in the XLSX file.

如果代码中需要遍历每一个sheet表格,需要range 循环

sheetsn := len(mySlice)   //sheet 个数rows :=len(mySlice[0])    //行数cols :=len(mySlice[0][0]) //列数

怎么读excel文件表格内容?

举个例子:




Go语言将数据写入excel go语言操作excel_字符串_05

准备读的文件



func xlxsreadtotable(pathname string){    var mySlice [][][]string       var err error       mySlice ,err= xlsx.FileToSliceUnmerged(pathname)    value := mySlice[0]    sheetsn := len(mySlice)   //sheet 个数      rows :=len(mySlice[0])    //行数       cols :=len(mySlice[0][0]) //列数       fmt.Println( value,err)    fmt.Println( sheetsn,cols,rows)          //            表 行 列       A1 := mySlice[0][0][0]   //这就是 A1       B1 := mySlice[0][0][1]   //这就是 B1       A2 := mySlice[0][1][0]  //A2       B2 := mySlice[0][1][1]  //B2       C1 := mySlice[0][0][2]  //C1       fmt.Println("A1:",A1,"A2:",A2,"B1:",B1,"B2:",B2,"C1:",C1)}




Go语言将数据写入excel go语言操作excel_Go_06


运行结果:


Go语言将数据写入excel go语言操作excel_文件行数 golang text_07

结果正确


如果使用OpenFile则代码会是这样:

func readxlsx(pathname string)  {   wb, err := xlsx.OpenFile(pathname)   if err != nil {panic(err)}   // wb 引用 workbook      fmt.Println("Sheets in this file:")   for i, sh := range wb.Sheets {      fmt.Println(i, sh.Name)   }   fmt.Println("----")}

那怎么改写一个excel的内容呢?

func editexlsx(pathname string)  {       //改写一下某cell       wb, _ := xlsx.OpenFile(pathname)     cell ,_:= wb.Sheet["Sheet1"].Cell(3,3)     cell.Value ="改写D4"   wb.Save(pathname)}

运行结果:


Go语言将数据写入excel go语言操作excel_字符串_08

D4格子被改写成功


看文档还支持各种,表格格式,字体大小,文字颜色。

func SetDefaultFont ¶ 设置字体和字体大小

func SetDefaultFont(size float64, name string)

func SkipEmptyCells ¶ 在Row.ForEachCell循环中跳过空cell

func SkipEmptyCells(flags *cellVisitorFlags)

SkipEmptyCells can be passed as an option to Row.ForEachCell in order to make it skip over empty cells in the sheet.

func SkipEmptyRows ¶ 同理也可跳过空行

func SkipEmptyRows(flags *rowVisitorFlags)

SkipEmptyRows can be passed to the Sheet.ForEachRow function to cause it to skip over empty Rows.

读写表格时,从表格得到时间需要用 TimeFromExcelTime()转换。

写表格时,时间需要转换成excel时间 TimeToExcelTime()。

如果表格超大,记得调用一下函数 UseDiskVCellStore(f *File)

如果表格较小,还可以全部放内存来加快表格处理,函数 UseMemoryCellStore(f *File)。

整数行列,可以直接转换到字符串,如下:

y := xlsx.RowIndexToString(2)x :=xlsx.ColIndexToLetters(3)   fmt.Println("x3:",x,"  y2:",y)

运行如下:


Go语言将数据写入excel go语言操作excel_文件行数 golang text_09

列索引3 即D,行索引2即第 3行


实际工作中,应该还需要整行写。就需要单独设计一个rowWrite函数,内部实现还是拆成一个个cell去写。

总结,

Go写Excel感觉上比Python还简单。坑少。