基于Beego框架的导入导出Excel

简介: 基于Beego框架的导入导出Excel,以及解决中文文件名乱码问题

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)

相关文章
|
5月前
|
easyexcel Java 测试技术
用 EasyExcel 实现 Excel 的导入导出
用 EasyExcel 实现 Excel 的导入导出
219 0
|
3月前
|
Java easyexcel Maven
【Java专题_04】集成EasyExcel进行Excel导入导出详细教程
【Java专题_04】集成EasyExcel进行Excel导入导出详细教程
|
4月前
|
前端开发
若依框架 ------- 导入导出(Excel)
若依框架 ------- 导入导出(Excel)
115 0
|
6月前
|
Java
SpringBoot实现Excel导入导出
SpringBoot实现Excel导入导出
64 0
|
6月前
|
开发框架 Java easyexcel
如何使用 SpringBoot 集成 EasyExcel 3.x 来实现优雅的 Excel 导入导出功能?
如何使用 SpringBoot 集成 EasyExcel 3.x 来实现优雅的 Excel 导入导出功能?
325 2
如何使用 SpringBoot 集成 EasyExcel 3.x 来实现优雅的 Excel 导入导出功能?
|
6月前
|
Java
Java Excel导入导出功能实现
Java Excel导入导出功能实现
50 0
|
7月前
|
存储 Java easyexcel
每日一博 - Excel导入导出的那点事儿
每日一博 - Excel导入导出的那点事儿
44 0
|
7月前
|
前端开发 计算机视觉
Excel | 前端实现复杂表格导入导出
通过前端技术实现复杂excel表格(合并单元格,这里没有做表格的数据类型)的导入导出,下面代码还有简单表格的导出。 以下代码,cv即可用。主要是vue3以及ts的简单写法。
|
9月前
|
JavaScript 前端开发
vue-admin-element框架实现简单的excel导出功能
导出功能是比较常见的功能之一,这里以一个简单的导出功能为示例,如果需要更复杂的导出功能,可以在此基础上进行丰富。
135 0
|
9月前
|
JavaScript 前端开发 Java