1.概述
导入导出功能是最常见的开发功能之一,这里用beego框架实现,这里采用 github.com/360EntSecGroup-Skylar/excelize 方式实现。
2.功能实现
2.1 安装
安装 github.com/360EntSecGroup-Skylar/excelize
go get -u github.com/360EntSecGroup-Skylar/excelize
2.2 实现代码
package controllers
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/astaxie/beego/logs"
"net/http"
"net/url"
"path"
"screen/components"
"screen/models"
"strconv"
"strings"
"time"
"github.com/astaxie/beego"
)
// TestController operations for Topo
type TestControllerstruct {
beego.Controller
}
// URLMapping ...
func (c *TestController) URLMapping() {
c.Mapping("ExportExcel", c.ExportExcel)
c.Mapping("ImportExcel", c.ImportExcel)
}
// ExportExcel ...
// @Title Get One
// @Description get Topo by id
// @Param id path string true "The key for staticblock"
// @Success 200 {object}
// @Failure 403 :id is empty
// @router /export/ [get]
func (c *TestController) ExportExcel() {
excelize.NewFile()
file := excelize.NewFile()
//设置表格头
title := getTitle()
file.SetSheetRow("Sheet1", "A1", title)
list, _ := models.GetTopoByIds(ids)
//写入数据
for i := 0; i < 10; i++ {
file.SetSheetRow("Sheet1", "A"+lint, &[]interface{}{
i, "name"+i,
})
}
//构造文件名称
fileName := "导出文件" + time.Now().Format("20060102150405") + ".xlsx"
// 解决文件名中文乱码问题
fileName = path.Base(fileName)
fileName = url.QueryEscape(fileName)
c.Ctx.Output.Header("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
c.Ctx.Output.Header("Content-Disposition", "attachment;filename="+fileName)
c.Ctx.Output.Header("Pragma", "No-cache")
c.Ctx.Output.Header("Cache-Control", "No-cache")
c.Ctx.Output.Header("Expires", "0")
var buffer bytes.Buffer
if err := file.Write(&buffer); err != nil {
logs.Error(err)
}
r := bytes.NewReader(buffer.Bytes())
http.ServeContent(c.Ctx.ResponseWriter, c.Ctx.Request, fileName, time.Now(), r)
}
func getTitle() *[]interface{} {
var titles = []interface{}{
"序号", "名称",
}
return &titles
}
// ImportExcel ...
// @Title ImportExcel
// @Description import Topo
// @Param body body true
// @Success 201 {int}
// @Failure 403 body is empty
// @router /import/ [post]
func (c *TestController) ImportExcel() {
file, h, _ := c.GetFile("file") //获取上传的文件
ext := path.Ext(h.Filename)
//验证后缀名是否符合要求
AllowExtMap := map[string]bool{
".xlsx": true,
}
if _, ok := AllowExtMap[ext]; !ok {
c.Data["json"] = "后缀名不符合上传要求"
c.ServeJSON()
return
}
xlsx, err := excelize.OpenReader(file)
if err != nil {
logs.Error(err)
c.Data["json"] = "读取文件异常"
c.ServeJSON()
return
}
rows := xlsx.GetRows("Sheet1")
if rows == nil || len(rows) == 0 {
c.Data["json"] = "Sheet1不存在或无数据"
c.ServeJSON()
return
}
// 验证表头是否一直
titleRow := rows[0]
title := getTitle()
for i, v := range *title {
value := titleRow[i]
if v != value {
c.Data["json"] = "标题不符合要求"
c.ServeJSON()
return
}
}
count := 0
for i, row := range rows {
if i > 0 {
fmt.Println(row[0], row[1])
count++
}
}
if count == 0 {
c.Data["json"] = "上传失败"
} else {
c.Data["json"] = "上传成功" + strconv.Itoa(count) + "条"
}
c.ServeJSON()
}
3.解决文件名中文乱码
如下代码,解决问题
// 解决文件名中文乱码问题
fileName = path.Base(fileName)
fileName = url.QueryEscape(fileName)