使用go实现导出excel表格代码比较固定,因此,可以抽取为工具函数,便于业务层复用。下面介绍简单一个封装函数,支持设置表头、数据内容,及简单样式。
二、实现步骤1. 导入依赖包
import "github.com/xuri/excelize/v2"这里选择主流的excel工具库。
2. 创建实例
函数签名:
func WriteToExcel(headers []string, data [][]interface{}, options ExcelOptions)创建文件、工作表:
file := excelize.NewFile()
sheetIndex := file.NewSheet(sheetName)
file.SetActiveSheet(sheetIndex) // 默认sheetSetActiveSheet 用来设置默认的工作表。
3. 设置表头
// 设置表头
for i, header := range headers {
tempColAxis := firstColAxis + int32(i)
writeCell(file, sheetName, tempColAxis, firstRowAxis, header)
}设置单元格内容封装在子函数writeCell。
4. 填充数据
// 设置内容
for i, line := range data {
tempRowAxis := firstRowAxis + i + 1
for j, item := range line {
tempColAxis := firstColAxis + int32(j)
writeCell(file, sheetName, tempColAxis, tempRowAxis, item)
}
}
// 设置单元格内容
func writeCell(file *excelize.File, sheetName string, collAxis int32, rowAxis int,
value interface{}) {
err := file.SetCellValue(sheetName, getCellIndex(collAxis, rowAxis), value)
if err != nil {
log.LogError("excel set cell value error:%v", err)
}
}
// 获取单元格下标
func getCellIndex(colAxis int32, rowAxis int) string {
return fmt.Sprintf("%c%d", colAxis, rowAxis)
}SetCellValue:填写的单元格下标,先列下标,再行下标。例如,第一行第一列:A1,第二行第三列:C2。
5. 设置样式
// 设置样式
func setStyle(file *excelize.File, sheetName string, maxCol int32, options ExcelOptions) {
err := file.SetColWidth(sheetName, string(firstColAxis), string(maxCol), options.ColWidth) // 设置列宽
if err != nil {
log.LogError("excel SetColWidth error:%v", err)
}
err = file.SetRowHeight(sheetName, firstRowAxis, options.RowHeight) // 设置行高
if err != nil {
log.LogError("excel SetRowHeight error:%v", err)
}
style := &excelize.Style{
Font: &excelize.Font{
Bold: true,
},
}
styleId, err := file.NewStyle(style)
if err != nil {
log.LogError("excel NewStyle error:%v", err)
}
err = file.SetCellStyle(sheetName, getCellIndex(firstColAxis, firstRowAxis), getCellIndex(maxCol, maxRow),
styleId)
if err != nil {
log.LogError("excel SetCellStyle error:%v", err)
}
}SetColWidth:设置列宽,需指定起止列。
SetRowHeight:设置行高,这里单设置表头的行高。
NewStyle:定义样式。
SetCellStyle:对指定区域,设置单元格样式。
6. 写到输出流
file.Write(httpWriter) 此处设置到http输出流,写本地文件则可以输出到文件,比较不常用。
三、注意点1. 通过http导出,需注意设置header。
Content-Disposition: fmt.Sprintf(`attachment; filename="%s"`, fileName)
Content-Type: application/vnd.ms-excel2. 设置样式需注意,哪些样式可以作用于什么范围,样式不生效多数是因为给对象(如单元格)设置了不可设置到单元格的样式,例如行高。