调整Excel导出时使用的方法
This commit is contained in:
174
excel/excel.go
174
excel/excel.go
@@ -163,12 +163,20 @@ func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportCo
|
||||
if exportData, ok := data.(ExportData); ok {
|
||||
// 使用接口方法获取数据
|
||||
rows = exportData.GetExportRows()
|
||||
// 如果接口返回nil,初始化为空切片
|
||||
if rows == nil {
|
||||
rows = [][]interface{}{}
|
||||
}
|
||||
} else {
|
||||
// 处理结构体切片
|
||||
// 处理结构体切片(包括nil和空切片的情况)
|
||||
rows, err = e.convertDataToRows(data, columns)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert data to rows: %w", err)
|
||||
}
|
||||
// 确保rows不为nil
|
||||
if rows == nil {
|
||||
rows = [][]interface{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// 写入数据行
|
||||
@@ -202,140 +210,11 @@ func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportCo
|
||||
return e.file.Write(w)
|
||||
}
|
||||
|
||||
// ExportToFile 导出数据到文件(黑盒模式,推荐使用)
|
||||
// filePath: 文件路径
|
||||
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
||||
// columns: 列定义
|
||||
// data: 数据列表
|
||||
// 返回错误信息
|
||||
//
|
||||
// 示例:
|
||||
//
|
||||
// excel := excel.NewExcel()
|
||||
// err := excel.ExportToFile("users.xlsx", "用户列表", columns, users)
|
||||
func (e *Excel) ExportToFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||
if e.file == nil {
|
||||
e.file = excelize.NewFile()
|
||||
}
|
||||
|
||||
// 设置工作表名称
|
||||
if sheetName == "" {
|
||||
sheetName = "Sheet1"
|
||||
}
|
||||
|
||||
// 检查工作表是否已存在
|
||||
sheetIndex, err := e.file.GetSheetIndex(sheetName)
|
||||
if err != nil || sheetIndex == 0 {
|
||||
// 工作表不存在,需要创建
|
||||
// 如果sheetName不是"Sheet1",且默认"Sheet1"存在,则删除它
|
||||
if sheetName != "Sheet1" {
|
||||
defaultIndex, _ := e.file.GetSheetIndex("Sheet1")
|
||||
if defaultIndex > 0 {
|
||||
e.file.DeleteSheet("Sheet1")
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新工作表
|
||||
_, err = e.file.NewSheet(sheetName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create sheet: %w", err)
|
||||
}
|
||||
|
||||
// 重新获取工作表索引
|
||||
sheetIndex, err = e.file.GetSheetIndex(sheetName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get sheet index: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 设置活动工作表
|
||||
if sheetIndex > 0 {
|
||||
e.file.SetActiveSheet(sheetIndex)
|
||||
}
|
||||
|
||||
// 写入表头
|
||||
headerStyle, _ := e.file.NewStyle(&excelize.Style{
|
||||
Font: &excelize.Font{
|
||||
Bold: true,
|
||||
Size: 12,
|
||||
},
|
||||
Fill: excelize.Fill{
|
||||
Type: "pattern",
|
||||
Color: []string{"#E0E0E0"},
|
||||
Pattern: 1,
|
||||
},
|
||||
Alignment: &excelize.Alignment{
|
||||
Horizontal: "center",
|
||||
Vertical: "center",
|
||||
},
|
||||
})
|
||||
|
||||
for i, col := range columns {
|
||||
cell := fmt.Sprintf("%c1", 'A'+i)
|
||||
e.file.SetCellValue(sheetName, cell, col.Header)
|
||||
|
||||
// 设置表头样式
|
||||
e.file.SetCellStyle(sheetName, cell, cell, headerStyle)
|
||||
|
||||
// 设置列宽
|
||||
if col.Width > 0 {
|
||||
colName, _ := excelize.ColumnNumberToName(i + 1)
|
||||
e.file.SetColWidth(sheetName, colName, colName, col.Width)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理数据
|
||||
var rows [][]interface{}
|
||||
|
||||
// 检查数据是否实现了ExportData接口
|
||||
if exportData, ok := data.(ExportData); ok {
|
||||
// 使用接口方法获取数据
|
||||
rows = exportData.GetExportRows()
|
||||
} else {
|
||||
// 处理结构体切片
|
||||
rows, err = e.convertDataToRows(data, columns)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert data to rows: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 写入数据行
|
||||
for rowIndex, row := range rows {
|
||||
for colIndex, value := range row {
|
||||
cell := fmt.Sprintf("%c%d", 'A'+colIndex, rowIndex+2) // +2 因为第一行是表头
|
||||
|
||||
// 应用格式化函数
|
||||
var cellValue interface{} = value
|
||||
if colIndex < len(columns) && columns[colIndex].Format != nil {
|
||||
cellValue = columns[colIndex].Format(value)
|
||||
}
|
||||
|
||||
e.file.SetCellValue(sheetName, cell, cellValue)
|
||||
}
|
||||
}
|
||||
|
||||
// 自动调整列宽(如果未设置宽度)
|
||||
for i, col := range columns {
|
||||
if col.Width == 0 {
|
||||
colName, _ := excelize.ColumnNumberToName(i + 1)
|
||||
// 获取列的最大宽度
|
||||
maxWidth := e.getColumnMaxWidth(sheetName, i+1, len(rows)+1)
|
||||
if maxWidth > 0 {
|
||||
e.file.SetColWidth(sheetName, colName, colName, maxWidth)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 保存文件
|
||||
return e.file.SaveAs(filePath)
|
||||
}
|
||||
|
||||
// GetFile 获取Excel文件对象(高级功能时使用)
|
||||
// 返回excelize.File对象,可用于高级操作
|
||||
//
|
||||
// ℹ️ 推荐使用黑盒方法:
|
||||
// - ExportToWriter():导出到Writer
|
||||
// - ExportToFile():导出到文件
|
||||
// - ExportToWriter():导出到Writer(可用于文件、HTTP响应等)
|
||||
//
|
||||
// 仅在需要使用高级功能时获取对象:
|
||||
// - 多工作表操作
|
||||
@@ -345,7 +224,9 @@ func (e *Excel) ExportToFile(filePath string, sheetName string, columns []Export
|
||||
// 示例(常用操作,推荐):
|
||||
//
|
||||
// excel := excel.NewExcel()
|
||||
// excel.ExportToFile("users.xlsx", "用户列表", columns, users)
|
||||
// file, _ := os.Create("users.xlsx")
|
||||
// defer file.Close()
|
||||
// excel.ExportToWriter(file, "用户列表", columns, users)
|
||||
//
|
||||
// 示例(高级功能):
|
||||
//
|
||||
@@ -360,15 +241,36 @@ func (e *Excel) GetFile() *excelize.File {
|
||||
}
|
||||
|
||||
// convertDataToRows 将数据转换为行数据
|
||||
// 支持nil、空切片等情况,返回空切片而不是错误
|
||||
func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][]interface{}, error) {
|
||||
// 如果data为nil,返回空切片
|
||||
if data == nil {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
|
||||
// 使用反射处理数据
|
||||
val := reflect.ValueOf(data)
|
||||
if val.Kind() == reflect.Ptr {
|
||||
// 如果是指针且指向nil,返回空切片
|
||||
if val.IsNil() {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
val = val.Elem()
|
||||
}
|
||||
|
||||
// 如果解引用后仍然是无效值,返回空切片
|
||||
if !val.IsValid() {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
|
||||
// 必须是切片类型
|
||||
if val.Kind() != reflect.Slice {
|
||||
return nil, fmt.Errorf("data must be a slice")
|
||||
return nil, fmt.Errorf("data must be a slice, got %v", val.Kind())
|
||||
}
|
||||
|
||||
// 如果是空切片,返回空切片(不返回错误)
|
||||
if val.Len() == 0 {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
|
||||
rows := make([][]interface{}, 0, val.Len())
|
||||
@@ -376,6 +278,12 @@ func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][
|
||||
for i := 0; i < val.Len(); i++ {
|
||||
item := val.Index(i)
|
||||
if item.Kind() == reflect.Ptr {
|
||||
// 如果指针指向nil,跳过该行或使用空值
|
||||
if item.IsNil() {
|
||||
row := make([]interface{}, len(columns))
|
||||
rows = append(rows, row)
|
||||
continue
|
||||
}
|
||||
item = item.Elem()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user