Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 38ebe73e45 | |||
| e3d9bbbcc5 |
113
docs/excel.md
113
docs/excel.md
@@ -13,30 +13,26 @@ Excel导出工具提供了将数据导出到Excel文件的功能,支持结构
|
|||||||
- **自定义格式化**:支持自定义字段值的格式化函数
|
- **自定义格式化**:支持自定义字段值的格式化函数
|
||||||
- **自动列宽**:自动调整列宽以适应内容
|
- **自动列宽**:自动调整列宽以适应内容
|
||||||
- **表头样式**:自动应用表头样式(加粗、背景色等)
|
- **表头样式**:自动应用表头样式(加粗、背景色等)
|
||||||
|
- **智能工作表管理**:自动处理工作表的创建和删除,避免产生空sheet
|
||||||
- **ExportData接口**:支持实现ExportData接口进行高级定制
|
- **ExportData接口**:支持实现ExportData接口进行高级定制
|
||||||
|
- **空数据处理**:即使数据为空(nil或空切片),也会正常生成表头
|
||||||
|
- **统一接口**:只暴露 `ExportToWriter` 一个核心方法
|
||||||
|
|
||||||
## 使用方法
|
## 使用方法
|
||||||
|
|
||||||
### 1. 创建工厂(推荐)
|
### 1. 创建工厂
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "git.toowon.com/jimmy/go-common/factory"
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
|
|
||||||
// 方式1:从配置文件创建(推荐)
|
// 从配置文件创建
|
||||||
fac, err := factory.NewFactoryFromFile("./config.json")
|
fac, err := factory.NewFactoryFromFile("./config.json")
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 方式2:从配置对象创建
|
// 或Excel导出不需要配置,可以传nil
|
||||||
cfg, _ := config.LoadFromFile("./config.json")
|
|
||||||
fac := factory.NewFactory(cfg)
|
|
||||||
|
|
||||||
// 方式3:Excel导出不需要配置,可以传nil
|
|
||||||
fac := factory.NewFactory(nil)
|
fac := factory.NewFactory(nil)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 导出结构体切片到文件(黑盒模式,推荐)
|
### 2. 导出结构体切片到文件
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 定义结构体
|
// 定义结构体
|
||||||
@@ -70,7 +66,7 @@ if err != nil {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 导出到HTTP响应(黑盒模式,推荐)
|
### 3. 导出到HTTP响应
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "net/http"
|
import "net/http"
|
||||||
@@ -102,7 +98,7 @@ func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. 使用格式化函数(黑盒模式,推荐)
|
### 4. 使用格式化函数
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "git.toowon.com/jimmy/go-common/excel"
|
import "git.toowon.com/jimmy/go-common/excel"
|
||||||
@@ -114,7 +110,7 @@ columns := []factory.ExportColumn{
|
|||||||
Header: "创建时间",
|
Header: "创建时间",
|
||||||
Field: "CreatedAt",
|
Field: "CreatedAt",
|
||||||
Width: 20,
|
Width: 20,
|
||||||
Format: excel.FormatDateTimeDefault, // 使用便捷的格式化函数
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime), // 使用适配器直接调用tools函数
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Header: "状态",
|
Header: "状态",
|
||||||
@@ -201,7 +197,7 @@ file.SetCellStyle("Sheet2", "A1", "A1", style)
|
|||||||
|
|
||||||
## API 参考
|
## API 参考
|
||||||
|
|
||||||
### 工厂方法(黑盒模式,推荐使用)
|
### 工厂方法
|
||||||
|
|
||||||
#### ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error
|
#### ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
@@ -215,9 +211,19 @@ file.SetCellStyle("Sheet2", "A1", "A1", style)
|
|||||||
|
|
||||||
**返回:** 错误信息
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**数据为空处理:**
|
||||||
|
- 支持 `nil`、空切片、指针类型等空数据情况
|
||||||
|
- 即使数据为空,表头也会正常生成
|
||||||
|
|
||||||
|
**工作表处理逻辑:**
|
||||||
|
- 如果 `sheetName` 为空,默认使用 "Sheet1"
|
||||||
|
- 如果指定的工作表不存在,会自动创建
|
||||||
|
- 使用自定义名称时会自动删除默认的"Sheet1",避免产生空sheet
|
||||||
|
|
||||||
**示例:**
|
**示例:**
|
||||||
```go
|
```go
|
||||||
fac.ExportToExcel(w, "用户列表", columns, users)
|
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
fac.ExportToExcel(w, "空数据", columns, []User{}) // 空数据也会生成表头
|
||||||
```
|
```
|
||||||
|
|
||||||
#### ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error
|
#### ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
@@ -228,13 +234,23 @@ fac.ExportToExcel(w, "用户列表", columns, users)
|
|||||||
- `filePath`: 文件路径
|
- `filePath`: 文件路径
|
||||||
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
- `columns`: 列定义
|
- `columns`: 列定义
|
||||||
- `data`: 数据列表
|
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
|
||||||
**返回:** 错误信息
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**实现说明:**
|
||||||
|
- 此方法内部创建文件并调用 `ExportToWriter`
|
||||||
|
- 文件相关的封装由工厂方法处理
|
||||||
|
|
||||||
|
**工作表处理逻辑:**
|
||||||
|
- 如果 `sheetName` 为空,默认使用 "Sheet1"
|
||||||
|
- 如果指定的工作表不存在,会自动创建
|
||||||
|
- 使用自定义名称时会自动删除默认的"Sheet1",避免产生空sheet
|
||||||
|
|
||||||
**示例:**
|
**示例:**
|
||||||
```go
|
```go
|
||||||
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
fac.ExportToExcelFile("empty.xlsx", "空数据", columns, []User{}) // 空数据也会生成表头
|
||||||
```
|
```
|
||||||
|
|
||||||
### 高级方法
|
### 高级方法
|
||||||
@@ -245,9 +261,7 @@ fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
|||||||
|
|
||||||
**返回:** Excel导出器对象和错误信息
|
**返回:** Excel导出器对象和错误信息
|
||||||
|
|
||||||
**说明:**
|
**说明:** 仅在需要使用高级功能时使用,推荐使用黑盒方法
|
||||||
- 仅在需要使用高级功能时使用
|
|
||||||
- 推荐使用黑盒方法:`ExportToExcel()`、`ExportToExcelFile()`
|
|
||||||
|
|
||||||
### 结构体类型
|
### 结构体类型
|
||||||
|
|
||||||
@@ -270,38 +284,40 @@ type ExportColumn struct {
|
|||||||
- `Width`: 列宽,0表示自动调整
|
- `Width`: 列宽,0表示自动调整
|
||||||
- `Format`: 格式化函数,用于自定义字段值的显示格式
|
- `Format`: 格式化函数,用于自定义字段值的显示格式
|
||||||
|
|
||||||
### 便捷函数
|
### 格式化函数适配器
|
||||||
|
|
||||||
#### excel.FormatDateTime(layout string) func(interface{}) string
|
#### excel.AdaptTimeFormatter(fn func(time.Time, ...string) string) func(interface{}) string
|
||||||
|
|
||||||
创建日期时间格式化函数。
|
适配器函数:将tools包的格式化函数转换为Excel Format字段需要的函数类型。
|
||||||
|
|
||||||
**参数:**
|
**参数:**
|
||||||
- `layout`: 时间格式,如 "2006-01-02 15:04:05"
|
- `fn`: tools包的格式化函数(如 `tools.FormatDate`、`tools.FormatDateTime` 等)
|
||||||
|
|
||||||
**返回:** 格式化函数
|
**返回:** Excel Format字段需要的格式化函数
|
||||||
|
|
||||||
|
**说明:**
|
||||||
|
- 允许直接使用tools包的任何格式化函数
|
||||||
|
|
||||||
**示例:**
|
**示例:**
|
||||||
```go
|
```go
|
||||||
Format: excel.FormatDateTime("2006-01-02 15:04:05")
|
import (
|
||||||
```
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
)
|
||||||
|
|
||||||
#### excel.FormatDate(value interface{}) string
|
// 使用tools.FormatDate
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDate)
|
||||||
|
|
||||||
格式化日期(格式:2006-01-02)。
|
// 使用tools.FormatDateTime
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime)
|
||||||
|
|
||||||
**示例:**
|
// 使用tools.FormatTime
|
||||||
```go
|
Format: excel.AdaptTimeFormatter(tools.FormatTime)
|
||||||
Format: excel.FormatDate
|
|
||||||
```
|
|
||||||
|
|
||||||
#### excel.FormatDateTimeDefault(value interface{}) string
|
// 使用自定义格式化函数
|
||||||
|
Format: excel.AdaptTimeFormatter(func(t time.Time) string {
|
||||||
格式化日期时间(格式:2006-01-02 15:04:05)。
|
return tools.Format(t, "2006-01-02 15:04:05", "Asia/Shanghai")
|
||||||
|
})
|
||||||
**示例:**
|
|
||||||
```go
|
|
||||||
Format: excel.FormatDateTimeDefault
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### ExportData接口
|
### ExportData接口
|
||||||
@@ -356,7 +372,7 @@ func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
Header: "创建时间",
|
Header: "创建时间",
|
||||||
Field: "CreatedAt",
|
Field: "CreatedAt",
|
||||||
Width: 20,
|
Width: 20,
|
||||||
Format: excel.FormatDateTimeDefault,
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Header: "状态",
|
Header: "状态",
|
||||||
@@ -394,31 +410,36 @@ func main() {
|
|||||||
|
|
||||||
## 设计优势
|
## 设计优势
|
||||||
|
|
||||||
### 优势总结
|
|
||||||
|
|
||||||
1. **降低复杂度**:调用方无需关心Excel文件对象的创建和管理
|
1. **降低复杂度**:调用方无需关心Excel文件对象的创建和管理
|
||||||
2. **延迟初始化**:Excel导出器在首次使用时才创建,提高性能
|
2. **延迟初始化**:Excel导出器在首次使用时才创建
|
||||||
3. **统一接口**:所有操作通过工厂方法调用,接口统一
|
3. **统一接口**:所有操作通过工厂方法调用
|
||||||
4. **灵活扩展**:支持结构体切片、自定义格式化、ExportData接口等多种方式
|
4. **灵活扩展**:支持结构体切片、自定义格式化、ExportData接口等多种方式
|
||||||
5. **自动优化**:自动调整列宽、应用表头样式等
|
5. **自动优化**:自动调整列宽、应用表头样式等
|
||||||
|
|
||||||
## 注意事项
|
## 注意事项
|
||||||
|
|
||||||
1. **配置检查**:Excel导出不需要配置,可以传nil创建工厂
|
1. **配置**:Excel导出不需要配置,可以传nil创建工厂
|
||||||
2. **错误处理**:所有方法都可能返回错误,需要正确处理
|
2. **错误处理**:所有方法都可能返回错误,需要正确处理
|
||||||
3. **延迟初始化**:Excel导出器在首次使用时才创建,首次调用可能稍慢
|
3. **延迟初始化**:Excel导出器在首次使用时才创建,首次调用可能稍慢
|
||||||
4. **字段名匹配**:Field字段名必须与结构体字段名匹配(区分大小写)
|
4. **字段名匹配**:Field字段名必须与结构体字段名匹配(区分大小写)
|
||||||
5. **嵌套字段**:支持嵌套字段访问(如 "User.Name"),但需要确保字段路径正确
|
5. **嵌套字段**:支持嵌套字段访问(如 "User.Name"),但需要确保字段路径正确
|
||||||
6. **格式化函数**:格式化函数返回的字符串会直接写入Excel单元格
|
6. **格式化函数**:格式化函数返回的字符串会直接写入Excel单元格
|
||||||
7. **列宽设置**:Width为0时会自动调整列宽,但可能影响性能(大数据量时建议设置固定宽度)
|
7. **列宽设置**:Width为0时会自动调整列宽,但可能影响性能(大数据量时建议设置固定宽度)
|
||||||
|
8. **工作表处理**:工具会自动处理工作表的创建和删除,确保不会产生空sheet
|
||||||
|
9. **空数据处理**:即使数据为 `nil` 或空切片,表头也会正常生成
|
||||||
|
10. **方法设计**:
|
||||||
|
- `excel` 包只暴露 `ExportToWriter` 一个核心方法
|
||||||
|
- 文件相关的封装由工厂方法 `ExportToExcelFile` 处理
|
||||||
|
|
||||||
## 最佳实践
|
## 最佳实践
|
||||||
|
|
||||||
1. **使用黑盒方法**:推荐使用 `ExportToExcel()` 和 `ExportToExcelFile()`,无需获取Excel对象
|
1. **使用工厂方法**:推荐使用 `ExportToExcel()` 和 `ExportToExcelFile()`
|
||||||
2. **设置列宽**:对于大数据量,建议设置固定列宽以提高性能
|
2. **设置列宽**:对于大数据量,建议设置固定列宽以提高性能
|
||||||
3. **使用格式化函数**:对于日期时间、状态等字段,使用格式化函数提高可读性
|
3. **使用格式化函数**:对于日期时间、状态等字段,使用格式化函数提高可读性
|
||||||
4. **错误处理**:始终检查导出方法的返回值
|
4. **错误处理**:始终检查导出方法的返回值
|
||||||
5. **HTTP响应**:导出到HTTP响应时,记得设置正确的Content-Type和Content-Disposition头
|
5. **HTTP响应**:导出到HTTP响应时,记得设置正确的Content-Type和Content-Disposition头
|
||||||
|
6. **工作表命名**:推荐使用有意义的工作表名称,工具会自动处理工作表的创建和删除
|
||||||
|
7. **空数据场景**:即使查询结果为空,也可以导出包含表头的Excel文件
|
||||||
|
|
||||||
## 示例
|
## 示例
|
||||||
|
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ columns := []factory.ExportColumn{
|
|||||||
Header: "创建时间",
|
Header: "创建时间",
|
||||||
Field: "CreatedAt",
|
Field: "CreatedAt",
|
||||||
Width: 20,
|
Width: 20,
|
||||||
Format: excel.FormatDateTimeDefault,
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/excel"
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
"git.toowon.com/jimmy/go-common/factory"
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// User 用户结构体示例
|
// User 用户结构体示例
|
||||||
@@ -111,7 +112,7 @@ func example3(fac *factory.Factory) {
|
|||||||
Header: "创建时间",
|
Header: "创建时间",
|
||||||
Field: "CreatedAt",
|
Field: "CreatedAt",
|
||||||
Width: 20,
|
Width: 20,
|
||||||
Format: excel.FormatDateTimeDefault, // 使用便捷的格式化函数
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime), // 使用适配器直接调用tools函数
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Header: "状态",
|
Header: "状态",
|
||||||
@@ -174,7 +175,7 @@ func (d *UserExportData) GetExportColumns() []excel.ExportColumn {
|
|||||||
Header: "创建时间",
|
Header: "创建时间",
|
||||||
Field: "CreatedAt",
|
Field: "CreatedAt",
|
||||||
Width: 20,
|
Width: 20,
|
||||||
Format: excel.FormatDateTimeDefault,
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Header: "状态",
|
Header: "状态",
|
||||||
@@ -230,4 +231,3 @@ func (w *mockResponseWriter) Write(data []byte) (int, error) {
|
|||||||
func (w *mockResponseWriter) WriteHeader(statusCode int) {
|
func (w *mockResponseWriter) WriteHeader(statusCode int) {
|
||||||
// 模拟实现
|
// 模拟实现
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
251
excel/excel.go
251
excel/excel.go
@@ -6,6 +6,7 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
"github.com/xuri/excelize/v2"
|
"github.com/xuri/excelize/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -94,21 +95,33 @@ func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportCo
|
|||||||
sheetName = "Sheet1"
|
sheetName = "Sheet1"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 删除默认工作表(如果存在)
|
// 检查工作表是否已存在
|
||||||
index, err := e.file.GetSheetIndex("Sheet1")
|
sheetIndex, err := e.file.GetSheetIndex(sheetName)
|
||||||
if err == nil && index > 0 {
|
if err != nil || sheetIndex == 0 {
|
||||||
e.file.DeleteSheet("Sheet1")
|
// 工作表不存在,需要创建
|
||||||
}
|
// 如果sheetName不是"Sheet1",且默认"Sheet1"存在,则删除它
|
||||||
|
if sheetName != "Sheet1" {
|
||||||
|
defaultIndex, _ := e.file.GetSheetIndex("Sheet1")
|
||||||
|
if defaultIndex > 0 {
|
||||||
|
e.file.DeleteSheet("Sheet1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 创建新工作表
|
// 创建新工作表
|
||||||
_, err = e.file.NewSheet(sheetName)
|
_, err = e.file.NewSheet(sheetName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create sheet: %w", err)
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置活动工作表
|
// 设置活动工作表
|
||||||
sheetIndex, err := e.file.GetSheetIndex(sheetName)
|
if sheetIndex > 0 {
|
||||||
if err == nil && sheetIndex > 0 {
|
|
||||||
e.file.SetActiveSheet(sheetIndex)
|
e.file.SetActiveSheet(sheetIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,12 +163,20 @@ func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportCo
|
|||||||
if exportData, ok := data.(ExportData); ok {
|
if exportData, ok := data.(ExportData); ok {
|
||||||
// 使用接口方法获取数据
|
// 使用接口方法获取数据
|
||||||
rows = exportData.GetExportRows()
|
rows = exportData.GetExportRows()
|
||||||
|
// 如果接口返回nil,初始化为空切片
|
||||||
|
if rows == nil {
|
||||||
|
rows = [][]interface{}{}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// 处理结构体切片
|
// 处理结构体切片(包括nil和空切片的情况)
|
||||||
rows, err = e.convertDataToRows(data, columns)
|
rows, err = e.convertDataToRows(data, columns)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to convert data to rows: %w", err)
|
return fmt.Errorf("failed to convert data to rows: %w", err)
|
||||||
}
|
}
|
||||||
|
// 确保rows不为nil
|
||||||
|
if rows == nil {
|
||||||
|
rows = [][]interface{}{}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 写入数据行
|
// 写入数据行
|
||||||
@@ -189,128 +210,11 @@ func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportCo
|
|||||||
return e.file.Write(w)
|
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"
|
|
||||||
}
|
|
||||||
|
|
||||||
// 删除默认工作表(如果存在)
|
|
||||||
index, err := e.file.GetSheetIndex("Sheet1")
|
|
||||||
if err == nil && index > 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 && 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文件对象(高级功能时使用)
|
// GetFile 获取Excel文件对象(高级功能时使用)
|
||||||
// 返回excelize.File对象,可用于高级操作
|
// 返回excelize.File对象,可用于高级操作
|
||||||
//
|
//
|
||||||
// ℹ️ 推荐使用黑盒方法:
|
// ℹ️ 推荐使用黑盒方法:
|
||||||
// - ExportToWriter():导出到Writer
|
// - ExportToWriter():导出到Writer(可用于文件、HTTP响应等)
|
||||||
// - ExportToFile():导出到文件
|
|
||||||
//
|
//
|
||||||
// 仅在需要使用高级功能时获取对象:
|
// 仅在需要使用高级功能时获取对象:
|
||||||
// - 多工作表操作
|
// - 多工作表操作
|
||||||
@@ -320,7 +224,9 @@ func (e *Excel) ExportToFile(filePath string, sheetName string, columns []Export
|
|||||||
// 示例(常用操作,推荐):
|
// 示例(常用操作,推荐):
|
||||||
//
|
//
|
||||||
// excel := excel.NewExcel()
|
// excel := excel.NewExcel()
|
||||||
// excel.ExportToFile("users.xlsx", "用户列表", columns, users)
|
// file, _ := os.Create("users.xlsx")
|
||||||
|
// defer file.Close()
|
||||||
|
// excel.ExportToWriter(file, "用户列表", columns, users)
|
||||||
//
|
//
|
||||||
// 示例(高级功能):
|
// 示例(高级功能):
|
||||||
//
|
//
|
||||||
@@ -335,15 +241,36 @@ func (e *Excel) GetFile() *excelize.File {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// convertDataToRows 将数据转换为行数据
|
// convertDataToRows 将数据转换为行数据
|
||||||
|
// 支持nil、空切片等情况,返回空切片而不是错误
|
||||||
func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][]interface{}, error) {
|
func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][]interface{}, error) {
|
||||||
|
// 如果data为nil,返回空切片
|
||||||
|
if data == nil {
|
||||||
|
return [][]interface{}{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// 使用反射处理数据
|
// 使用反射处理数据
|
||||||
val := reflect.ValueOf(data)
|
val := reflect.ValueOf(data)
|
||||||
if val.Kind() == reflect.Ptr {
|
if val.Kind() == reflect.Ptr {
|
||||||
|
// 如果是指针且指向nil,返回空切片
|
||||||
|
if val.IsNil() {
|
||||||
|
return [][]interface{}{}, nil
|
||||||
|
}
|
||||||
val = val.Elem()
|
val = val.Elem()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 如果解引用后仍然是无效值,返回空切片
|
||||||
|
if !val.IsValid() {
|
||||||
|
return [][]interface{}{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 必须是切片类型
|
||||||
if val.Kind() != reflect.Slice {
|
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())
|
rows := make([][]interface{}, 0, val.Len())
|
||||||
@@ -351,6 +278,12 @@ func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][
|
|||||||
for i := 0; i < val.Len(); i++ {
|
for i := 0; i < val.Len(); i++ {
|
||||||
item := val.Index(i)
|
item := val.Index(i)
|
||||||
if item.Kind() == reflect.Ptr {
|
if item.Kind() == reflect.Ptr {
|
||||||
|
// 如果指针指向nil,跳过该行或使用空值
|
||||||
|
if item.IsNil() {
|
||||||
|
row := make([]interface{}, len(columns))
|
||||||
|
rows = append(rows, row)
|
||||||
|
continue
|
||||||
|
}
|
||||||
item = item.Elem()
|
item = item.Elem()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -451,31 +384,49 @@ func (e *Excel) getColumnMaxWidth(sheetName string, colIndex int, maxRow int) fl
|
|||||||
return maxWidth
|
return maxWidth
|
||||||
}
|
}
|
||||||
|
|
||||||
// FormatDateTime 格式化日期时间(便捷函数)
|
// AdaptTimeFormatter 适配器函数:将tools包的格式化函数转换为Excel Format字段需要的函数类型
|
||||||
// 用于ExportColumn的Format字段
|
// 允许直接使用tools包的任何格式化函数
|
||||||
func FormatDateTime(layout string) func(interface{}) string {
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// // 直接使用tools.FormatDate
|
||||||
|
// Format: excel.AdaptTimeFormatter(tools.FormatDate)
|
||||||
|
//
|
||||||
|
// // 使用自定义格式化函数
|
||||||
|
// Format: excel.AdaptTimeFormatter(func(t time.Time) string {
|
||||||
|
// return tools.Format(t, "2006-01-02 15:04:05", "Asia/Shanghai")
|
||||||
|
// })
|
||||||
|
func AdaptTimeFormatter(fn func(time.Time, ...string) string) func(interface{}) string {
|
||||||
return func(value interface{}) string {
|
return func(value interface{}) string {
|
||||||
if t, ok := value.(time.Time); ok {
|
if t, ok := value.(time.Time); ok {
|
||||||
return t.Format(layout)
|
return fn(t)
|
||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// FormatDate 格式化日期(便捷函数)
|
// formatDateTime 格式化日期时间(内部便捷函数)
|
||||||
// 用于ExportColumn的Format字段,格式:2006-01-02
|
// 用于ExportColumn的Format字段
|
||||||
func FormatDate(value interface{}) string {
|
// layout: 时间格式,如 "2006-01-02 15:04:05"
|
||||||
if t, ok := value.(time.Time); ok {
|
// timezone: 可选时区,如果为空则使用时间对象本身的时区
|
||||||
return t.Format("2006-01-02")
|
// 直接调用 tools.Format() 方法
|
||||||
}
|
func formatDateTime(layout string, timezone ...string) func(interface{}) string {
|
||||||
return ""
|
return AdaptTimeFormatter(func(t time.Time, _ ...string) string {
|
||||||
|
return tools.Format(t, layout, timezone...)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// FormatDateTimeDefault 格式化日期时间(便捷函数)
|
// formatDate 格式化日期(内部便捷函数)
|
||||||
|
// 用于ExportColumn的Format字段,格式:2006-01-02
|
||||||
|
// 直接调用 tools.FormatDate() 方法
|
||||||
|
var formatDate = AdaptTimeFormatter(tools.FormatDate)
|
||||||
|
|
||||||
|
// formatDateTimeDefault 格式化日期时间(内部便捷函数)
|
||||||
// 用于ExportColumn的Format字段,格式:2006-01-02 15:04:05
|
// 用于ExportColumn的Format字段,格式:2006-01-02 15:04:05
|
||||||
func FormatDateTimeDefault(value interface{}) string {
|
// 直接调用 tools.FormatDateTime() 方法
|
||||||
if t, ok := value.(time.Time); ok {
|
var formatDateTimeDefault = AdaptTimeFormatter(tools.FormatDateTime)
|
||||||
return t.Format("2006-01-02 15:04:05")
|
|
||||||
}
|
// formatTime 格式化时间(内部便捷函数)
|
||||||
return ""
|
// 用于ExportColumn的Format字段,格式:15:04:05
|
||||||
}
|
// 直接调用 tools.FormatTime() 方法
|
||||||
|
var formatTime = AdaptTimeFormatter(tools.FormatTime)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -1648,16 +1649,27 @@ func (f *Factory) ExportToExcel(w io.Writer, sheetName string, columns []ExportC
|
|||||||
// filePath: 文件路径
|
// filePath: 文件路径
|
||||||
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
||||||
// columns: 列定义
|
// columns: 列定义
|
||||||
// data: 数据列表
|
// data: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
// 返回错误信息
|
// 返回错误信息
|
||||||
//
|
//
|
||||||
// 示例:
|
// 示例:
|
||||||
//
|
//
|
||||||
// fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
// fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
//
|
||||||
|
// 注意:此方法内部创建文件并调用 ExportToWriter,确保行为与 ExportToExcel 一致
|
||||||
func (f *Factory) ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error {
|
func (f *Factory) ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||||
e, err := f.getExcelClient()
|
e, err := f.getExcelClient()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return e.ExportToFile(filePath, sheetName, columns, data)
|
|
||||||
|
// 创建文件
|
||||||
|
file, err := os.Create(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create file: %w", err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
// 调用 ExportToWriter,复用核心逻辑
|
||||||
|
return e.ExportToWriter(file, sheetName, columns, data)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user