推荐阅读
【系列好文】go-zero从入门到精通(看了就会)
教程地址:https://blog.csdn.net/u011019141/article/details/139619172
go-zero整合Excelize并实现Excel导入导出
本教程基于go-zero微服务入门教程
,项目工程结构同上一个教程。
本教程主要实现go-zero框架整合Excelize,并暴露接口实现Excel模板下载、Excel导入、Excel导出。
go-zero微服务入门教程:https://blog.csdn.net/u011019141/article/details/136233473
本文源码:https://gitee.com/songfayuan/go-zero-demo (教程源码分支:6.zero整合Excelize操作Excel)
准备工作
- 如不熟悉go-zero项目的,请先查看上一篇
go-zero微服务入门教程
。
安装依赖
项目工程父级目录下执行如下指令安装依赖:
# 下载安装Excelize
go get github.com/xuri/excelize/v2
编写API Gateway代码
编写api文件
excel.api
在api目录下创建新目录doc/excel,在excel目录下创建excel.api文件。
syntax = "v1"
info(
title: "excel操作相关"
desc: "excel操作相关"
author: "宋发元"
)
type (
ExcelImportReq {
DeptId string `json:"deptId"` // 部门id(Content-Type: form-data)
File interface{} `json:"file,optional"` // excel文件(Content-Type: form-data)
}
ExcelImportData {
Total int64 `json:"total"` // 导入总数
Success int64 `json:"success"` // 导入成功数
Msg string `json:"msg"` // 提示信息
}
ExcelImportResp {
Code int64 `json:"code"`
Message string `json:"message"`
Data ExcelImportData `json:"data"`
}
ExcelExportlReq{
TimeStart string `form:"timeStart,optional"` // 时间(开始) yyyy-mm-dd
TimeEnd string `form:"timeEnd,optional"` // 时间(结束) yyyy-mm-dd
}
DefaultResponse {
Code int64 `json:"code,default=200"`
Message string `json:"message,default=操作成功"`
}
)
@server(
group : excel/test
prefix : /excel/test
)
service admin-api {
@doc (
summary :"excel模板下载"
)
@handler ExcelTemplateDownload
get /excel/templateDownload
@doc(
summary :"excel导入"
)
@handler ExcelImport
post /excel/excelImport (ExcelImportReq) returns (ExcelImportResp)
@doc(
summary :"excel导出"
)
@handler ExcelExport
get /excel/excelExport (ExcelExportlReq)returns (DefaultResponse)
}
admin.api
在api/doc/admin.api文件添加配置信息。
import "excel/excel.api"
用goctl生成API Gateway代码
生成方法同上篇文章,自行查看。但是此处要基于admin.api文件去生成代码,如果基于excel.api生成,则生成的代码只有excel.api定义的接口代码,其他api文件定义的接口代码不被生成。
api新增文件操作配置
以下操作在api模块执行。
admin-api.yaml
admin-api.yaml配置文件新增文件操作配置信息,如下:
#文件
UploadFile:
MaxFileNum: 100
MaxFileSize: 104857600 # 100MB
SavePath: template/uploads/
TemplatePath: template/excel/
config.go
config.go文件中新增UploadFile配置信息,如下:
type Config struct {
rest.RestConf
SysRpc zrpc.RpcClientConf
//这里新增
UploadFile UploadFile
}
type UploadFile struct {
MaxFileNum int64
MaxFileSize int64
SavePath string
TemplatePath string
}
修改API Gateway代码
exceltemplatedownloadlogic.go
修改api/internal/logic/excel/test/exceltemplatedownloadlogic.go
里的ExcelTemplateDownload
方法,完整代码如下:
package test
import (
"context"
"go-zero-demo/common/errors/errorx"
"net/http"
"os"
"github.com/zeromicro/go-zero/core/logx"
"go-zero-demo/api/internal/svc"
)
type ExcelTemplateDownloadLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
writer http.ResponseWriter
}
func NewExcelTemplateDownloadLogic(ctx context.Context, svcCtx *svc.ServiceContext, writer http.ResponseWriter) *ExcelTemplateDownloadLogic {
return &ExcelTemplateDownloadLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
writer: writer,
}
}
func (l *ExcelTemplateDownloadLogic) ExcelTemplateDownload() (err error) {
SavePath := l.svcCtx.Config.UploadFile.TemplatePath
filePath := "demo_excel_template.xlsx"
fullPath := SavePath + filePath
fileName := "Excel导入模板.xlsx"
//fullPath = "/Users/songfayuan/GolandProjects/go-zero-demo/template/excel/demo_excel_template.xlsx" //测试地址,绝对路径
_, err = os.Stat(fullPath)
if err != nil || os.IsNotExist(err) {
return errorx.New("文件不存在")
}
bytes, err := os.ReadFile(fullPath)
if err != nil {
return errorx.New("读取文件失败")
}
l.writer.Header().Add("Content-Type", "application/octet-stream")
l.writer.Header().Add("Content-Disposition", "attachment; filename= "+fileName)
l.writer.Write(bytes)
return
}
excelimportlogic.go
修改api/internal/logic/excel/test/excelimportlogic.go
里的ExcelImport
方法,完整代码如下:
package test
import (
"context"
"fmt"
"github.com/xuri/excelize/v2"
"github.com/zeromicro/go-zero/core/mapping"
"go-zero-demo/common/errors/errorx"
"go-zero-demo/common/utils"
"path/filepath"
"strings"
"go-zero-demo/api/internal/svc"
"go-zero-demo/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type ExcelImportLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
type excelDataForDept struct {
DeptId string `json:"DeptId,optional" excel:"col=1"` // 第1列:部门id
ParentDeptId string `json:"ParentDeptId,optional" excel:"col=2"` // 第2列:上级部门id
D