当前位置:网站首页>Go excel export tool encapsulation
Go excel export tool encapsulation
2022-06-24 06:36:00 【Johns】
1. Relevant database research
Recently in use go Develop a management side , Need to provide a Excel Export function . So I went to investigate Go Two commonly used Excel library :
tealeg/xlsx Simple to use , But it has limited functionality , Only string types can be inserted in cells . I went into its warehouse to have a look , It is found that this library is not maintained .
excelize It's more complicated to use , You need to specify excel Of sheet Coordinates to locate cells for reading or inserting data , But it's more powerful . The warehouse is still being maintained , I mentioned before issue, I replied in half a day .
After comparing the two libraries , Decision based on excelize Encapsulate a tool method , You only need to specify the header and data each time .
2. Encapsulates the code
Reference resources excelize The official demo, Find it every time you write excel You need to specify the content in Sheet Coordinates of .Sheet The coordinates of are divided into column coordinates and row coordinates .
- Column coordinates : A~Z, ( A~Z)( A~Z), ( A~Z)( A~Z)( A~Z) .... 1~26 Column use A~Z Express . exceed 26 Column is less than 676 Column from AA Begin and end at ZZ, Greater than 676 From the AAA Start , And so on .
- Row coordinates : from 1 Start to 1048576, The excess part needs to be cut to the next Sheet 了
package utils
/**
* @Description
* @Author ggr
* @Date 2021/7/8 21:06
**/
import (
"github.com/360EntSecGroup-Skylar/excelize/v2"
"strconv"
)
// maxCharCount most 26 Characters A-Z
const maxCharCount = 26
// ExportExcel export Excel file
// sheetName Worksheet name , Be careful not to take... Here sheet1 This kind of name , Otherwise, some errors will occur when the file is opened .
// headers Column name slice , Header
// rows Data slicing , Is a two-dimensional array
func ExportExcel(sheetName string, headers []string, rows [][]interface{}) (*excelize.File, error) {
f := excelize.NewFile()
sheetIndex := f.NewSheet(sheetName)
maxColumnRowNameLen := 1 + len(strconv.Itoa(len(rows)))
columnCount := len(headers)
if columnCount > maxCharCount {
maxColumnRowNameLen++
} else if columnCount > maxCharCount*maxCharCount {
maxColumnRowNameLen += 2
}
columnNames := make([][]byte, 0, columnCount)
for i, header := range headers {
columnName := getColumnName(i, maxColumnRowNameLen)
columnNames = append(columnNames, columnName)
// initialization excel Header , there index from 1 Pay attention to
curColumnName := getColumnRowName(columnName, 1)
err := f.SetCellValue(sheetName, curColumnName, header)
if err != nil {
return nil, err
}
}
for rowIndex, row := range rows {
for columnIndex, columnName := range columnNames {
// Start with the second line
err := f.SetCellValue(sheetName, getColumnRowName(columnName, rowIndex+2), row[columnIndex])
if err != nil {
return nil, err
}
}
}
f.SetActiveSheet(sheetIndex)
return f, nil
}
// getColumnName Generate column names
// Excel The column name rule of is from A-Z Stand back ; exceed Z In the future, it will be indicated by two letters , such as AA,AB,AC; If two letters are not enough, use three letters to indicate , such as AAA,AAB,AAC
// Here we map numbers to column names :0 -> A, 1 -> B, 2 -> C
// maxColumnRowNameLen Indicates the maximum length of the name box , Suppose the data is 10 That's ok ,1000 Column , Then the last name box is J1000( If there is a header , It is J1001), yes 4 position
// Here, according to maxColumnRowNameLen Generate slice , This slice can be reused later when the name box is generated , Without capacity expansion
func getColumnName(column, maxColumnRowNameLen int) []byte {
const A = 'A'
if column < maxCharCount {
// Allocate the slice capacity for the first time
slice := make([]byte, 0, maxColumnRowNameLen)
return append(slice, byte(A+column))
} else {
// Recursive generation is similar to AA,AB,AAA,AAB This form of column name
return append(getColumnName(column/maxCharCount-1, maxColumnRowNameLen), byte(A+column%maxCharCount))
}
}
// getColumnRowName Generate name box
// Excel The name box of the is A1,A2,B1,B2 To represent the , Here, you need to pass in the column name slice generated in the previous step , Then add the uplink index directly to generate the name box , There is no need to allocate memory every time
func getColumnRowName(columnName []byte, rowIndex int) (columnRowName string) {
l := len(columnName)
columnName = strconv.AppendInt(columnName, int64(rowIndex), 10)
columnRowName = string(columnName)
// Restore the column name
columnName = columnName[:l]
return
}3. The test case
func TestExportExcel(t *testing.T) {
t.Run("", func(t *testing.T) {
headers := []string{" user name ", " Gender ", " Age "}
values := [][]interface{}{
{" test ", "1", " male "},
{
"ggr1", "1", " male ",
},
}
f, _ := ExportExcel("sheet1", headers, values)
err := f.SaveAs("test.xlsx")
fmt.Sprintln(err)
})
}If you want to be in web Use , excelize.File Provides a Write Method , You can write it to http.ResponseWriter object w in , And set the following response header .
// The file name is in English , Otherwise, the Chinese code will be disordered
fileName = "test.xlxs"
w.Header().Add("Content-Type", "application/octet-stream")
w.Header().Add("Content-Disposition", "attachment; filename="+fileName)
w.Header().Add("Content-Transfer-Encoding", "binary")4. Record on pit
I was using excelize yes v2.4.0 Version of , This version of SheetName The parameter is case sensitive and cannot be set to sheet1, Otherwise, some errors will be reported when you open the file . It took a long time to find out .
Specific questions have been submitted issuer Give it to excelize It's official , The official replied in time and informed that it would be updated in the next version , That's great .
边栏推荐
- Use of SAP QM inspection points
- SQL server memory management on cloud
- Station B collapsed. Let's talk to the injured programmers
- Royal treasure: an analysis of SQL algebra optimization
- Rhel8 series update image Yum source is Tencent cloud Yum source
- How to batch move topics to different categories in discover
- Multi objective Optimization Practice Based on esmm model -- shopping mall
- Correct way to update Fedora image Yum source to Tencent cloud Yum source
- How to give full play to the advantages of Internet of things by edge computing intelligent gateway
- Come on, it's not easy for big factories to do projects!
猜你喜欢

The product layout is strengthened, the transformation of digital intelligence is accelerated, and FAW Toyota has hit 2022million annual sales
Oracle case: ohasd crash on AIX
![[fault announcement] one stored procedure brings down the entire database](/img/7c/e5adda73a077fe4b8f04b59d1e0e1e.jpg)
[fault announcement] one stored procedure brings down the entire database
![跳跃游戏II[贪心练习]](/img/e4/f59bb1f5137495ea357462100e2b38.png)
跳跃游戏II[贪心练习]

C语言学生管理系统——可检查用户输入合法性,双向带头循环链表

leetcode:84. 柱状图中最大的矩形

【二叉数学习】—— 树的介绍

【二叉树】——二叉树中序遍历

leetcode:85. 最大矩形

【JUC系列】Executor框架之CompletionFuture
随机推荐
The gadgets developed by freshmen are popular. Netizen: my food is good
Spirit information development log (3)
SQL server memory management on cloud
Operation and maintenance dry goods | how to improve the business stability and continuity through fault recovery?
Oracle case: ohasd crash on AIX
How to choose CMS website system for website construction
A cigarette of time to talk with you about how novices transform from functional testing to advanced automated testing
Attack and defense enlightenment: chromium component risk analysis and convergence
leetcode:85. 最大矩形
Coding and codesign: make design and development easier
Comparison of common layout solutions (media query, percentage, REM and vw/vh)
In the half year, there were 2.14 million paying users, a year-on-year increase of 62.5%, and New Oriental online launched its private domain
项目Demo
Excellent tech sharing | research and application of Tencent excellent map in weak surveillance target location
Another authoritative recommendation! Tencent zero trust was recognized by omdia Report
Command ‘[‘where‘, ‘cl‘]‘ returned non-zero exit status 1.
Quick reference table of PHP security configuration maintained by OWASP
Nature Neuroscience: challenges and future directions of functional brain tissue characterization
Wordpress5.8 is coming, and the updated website is faster!
What is the role of website domain name