go语言web开发系列之二十:用gorm+excelize库生成excel表格并下载

一,安装所需的库

1,excelize库的地址:

GitHub - qax-os/excelize: Go language library for reading and writing Microsoft Excel™ (XLAM / XLSM / XLSX / XLTM / XLTX) spreadsheets

,excelize库的文档:

介绍 · Excelize 简体字文档

2,excelize库的安装命令:

liuhongdi@ku:~$ go get -u github.com/360EntSecGroup-Skylar/excelize/v2

3,gorm库的官网地址:

GORM - The fantastic ORM library for Golang, aims to be developer friendly.

4,gorm库安装:

liuhongdi@ku:~$ go get -u gorm.io/gorm

说明:刘宏缔的go森林是一个专注golang的博客,
网站:https://blog.imgtouch.com
原文: go语言web开发系列之二十:用gorm+excelize库生成excel表格并下载 – 架构森林

说明:作者:刘宏缔 邮箱: [email protected]

二,演示项目的相关信息

1,地址:

GitHub - liuhongdi/digv20: 用gorm+excelize库生成excel表格并下载

2,功能说明:演示了从mysql数据库读取数据后导出到excel文件

3,项目结构:如图:

go语言web开发系列之二十:用gorm+excelize库生成excel表格并下载_第1张图片

三,sql代码

1,建表sql

CREATE TABLE `goods` (
 `goodsId` int NOT NULL AUTO_INCREMENT COMMENT 'id',
 `goodsName` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '' COMMENT '商品名称',
 `subject` varchar(200) NOT NULL DEFAULT '' COMMENT '标题',
 `price` decimal(15,2) NOT NULL DEFAULT '0.00' COMMENT '价格',
 `stock` int NOT NULL DEFAULT '0' COMMENT '库存数量',
 PRIMARY KEY (`goodsId`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='商品表'

2,插入演示数据:

INSERT INTO `goods` (`goodsId`, `goodsName`, `subject`, `price`, `stock`) VALUES
(1, '蜂蜜牛奶手工皂', '深入滋养,肌肤细腻嫩滑', '70.00', 100),
(2, '紫光筷子筒', '紫光智护,干爽防潮更健康', '189.00', 40),
(3, '野性mini便携式蓝牙音箱', '强悍机能,品味豪迈', '499.00', 100),
(4, '乐穿梭茶具', '茶具+茶叶精美端午礼盒', '200.00', 40);

四,go代码说明

1,pkg/file/excel.go

package file

import (
	"fmt"
	"github.com/gin-gonic/gin"
)
//excel文件下载
func FileExcelDown(c *gin.Context,filepath string,filename string) {
	//filename := "php_errors.log"
	c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
	c.Writer.Header().Add("Content-Type", "application/msexcel")
	c.File(filepath)
}

2,model/goods.go

package model

type Goods struct {
	GoodsId	int64  `gorm:"column:goodsId",json:"goodsid"` // 自增
	GoodsName string  `gorm:"column:goodsName",json:"goodsname"` //
	Subject string `gorm:"column:subject",json:"subject"`
	Price string `gorm:"column:price",json:"price"`
	Stock string `gorm:"column:stock",json:"stock"`
}

func (Goods) TableName() string {
	return "goods"
}

3,global/db.go

package global

import (
	"gorm.io/gorm"
	"time"
	"gorm.io/driver/mysql"
)

var (
	DBLink *gorm.DB
)

//创建mysql链接
func SetupDBLink() (error) {
	var err error
	dsn:="root:password@tcp(127.0.0.1:3306)/business?charset=utf8&parseTime=True&loc=Local";
	DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	//DBLink.Logger.LogMode(true)
	if err != nil {
		return err
	}
	sqlDB, err := DBLink.DB()
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)
	// SetMaxOpenConns 设置打开数据库连接的最大数量
	sqlDB.SetMaxOpenConns(30)
	// SetConnMaxLifetime 设置了连接可复用的最大时间
	sqlDB.SetConnMaxLifetime(time.Hour)
	return nil
}

4,service/goods.go

package service

import (
	"github.com/liuhongdi/digv20/dao"
	"github.com/liuhongdi/digv20/model"
)

//得到多件商品返回
func GetGoodsList() ([]*model.Goods,error) {
	goods, err := dao.SelectAllGoods()
    return goods,err
}

5,dao/goods.go

package dao

import (
	"github.com/liuhongdi/digv20/global"
	"github.com/liuhongdi/digv20/model"
)

func SelectAllGoods() ([]*model.Goods, error) {
	var goods []*model.Goods
	global.DBLink.Find(&goods)
	return goods, nil
}

6,controller/fileController.go

package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/liuhongdi/digv20/pkg/file"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/liuhongdi/digv20/service"
	"strconv"
)

type FileController struct{}

func NewFileController() FileController {
	return FileController{}
}

//下载一个txt文件
func (a *FileController) DownTxt(c *gin.Context) {
	filepath:="/data/logs/phplogs/php_errors.log"
	if (file.FileExist(filepath) == true) {
		fmt.Println("file exist")
	} else {
		fmt.Println("file not exist")
	}

	filename := "php_errors.log"
	file.FileDown(c,filepath,filename)
}

//生成并下载一个excel文件
func (a *FileController) DownExcel(c *gin.Context) {

	//创建新excel文件
	f := excelize.NewFile()
	// Create a new sheet.
	index := f.NewSheet("Sheet2")
	// Set value of a cell.
	f.SetCellValue("Sheet2", "A2", "Hello world.")
	f.SetCellValue("Sheet1", "B2", 100)
	// Set active sheet of the workbook.
	f.SetActiveSheet(index)

	//new sheet
	 f.NewSheet("Sheet3")

	//设置第1行行高
	err_h := f.SetRowHeight("Sheet3", 1, 80)
	if (err_h != nil) {
		fmt.Println(err_h)
	}
	//设置第2行行高
	err_h2 := f.SetRowHeight("Sheet3", 2, 40)
	if (err_h2 != nil) {
		fmt.Println(err_h2)
	}
	//合并单元格A1到E1
	err3 := f.MergeCell("Sheet3", "A1", "E1")
    if (err3 != nil) {
		fmt.Println(err3)
	}

	//设置B列列宽column width
	errwb := f.SetColWidth("Sheet3", "B", "B", 30)
	if (errwb != nil) {
		fmt.Println(errwb)
	}
	//设置C列列宽
	errwc := f.SetColWidth("Sheet3", "C", "C", 40)
	if (errwc != nil) {
		fmt.Println(errwc)
	}
	//设置标题的样式
	f.SetCellValue("Sheet3", "A1", "商品信息表")
	style, err := f.NewStyle(`{
   "fill":{"type":"pattern","color":["#E0EBF5"],"pattern":1},
    "font":
    {
        "bold": true,
        "italic": false,
        "family": "Times New Roman",
        "size": 36,
        "color": "#777777"
    },
"alignment":
    {
        "horizontal": "center",
        "ident": 1,
        "justify_last_line": true,
        "reading_order": 0,
        "relative_indent": 1,
        "shrink_to_fit": true,
        "vertical": "center",
        "wrap_text": true
    }
}`)

	if err != nil {
		fmt.Println(err)
	}
	errStyle := f.SetCellStyle("Sheet3", "A1", "E1", style)
	if errStyle != nil {
		fmt.Println(errStyle)
	}

	//为表头设置样式,第2行
	style2, errst := f.NewStyle(`{
    "font":
    {
        "bold": false,
        "italic": false,
        "family": "Times New Roman",
        "size": 12,
        "color": "#0000ff"
    },
"alignment":
    {
        "horizontal": "center",
        "ident": 1,
        "justify_last_line": true,
        "reading_order": 0,
        "relative_indent": 1,
        "shrink_to_fit": true,
        "vertical": "center",
        "wrap_text": true
    }
}`)
	if errst != nil {
		fmt.Println(errst)
	}
	errStyle2 := f.SetCellStyle("Sheet3", "A2", "E2", style2)
	if errStyle2 != nil {
		fmt.Println(errStyle2)
	}

    //设置表头的值
	f.SetCellValue("Sheet3", "A2", "id")
	f.SetCellValue("Sheet3", "B2", "商品名称")
	f.SetCellValue("Sheet3", "C2", "商品描述")
	f.SetCellValue("Sheet3", "D2", "商品价格")
	f.SetCellValue("Sheet3", "E2", "库存数量")
	//写入数据
	//得到商品列表
	goods,err := service.GetGoodsList()
    fmt.Println(goods)

    //遍历商品
    for i,v := range goods {
		fmt.Println(i)
    	fmt.Println(v)
		curIndex := i+3
		strIndex := strconv.Itoa(curIndex)
		f.SetCellValue("Sheet3", "A"+strIndex, v.GoodsId)
		f.SetCellValue("Sheet3", "B"+strIndex, v.GoodsName)
		f.SetCellValue("Sheet3", "C"+strIndex, v.Subject)
		f.SetCellValue("Sheet3", "D"+strIndex, v.Price)
		f.SetCellValue("Sheet3", "E"+strIndex, v.Stock)
	}

	//保存成文件
	filepath:="/data/temp/Book1.xlsx"
	filename:="Book1.xlsx"
	err5 := f.SaveAs(filepath);
	// Save spreadsheet by the given path.
	if  err5 != nil {
		fmt.Println(err5)
	} else {
		//下载
		file.FileExcelDown(c,filepath,filename)
	}
}

7,其他相关代码可访问github查看

五,测试效果

1,测试下载:

访问:

127.0.0.1:8080/file/downexcel

返回:

go语言web开发系列之二十:用gorm+excelize库生成excel表格并下载_第2张图片

2,打开excel文件查看:

go语言web开发系列之二十:用gorm+excelize库生成excel表格并下载_第3张图片

六,查看库的版本:

module github.com/liuhongdi/digv20

go 1.15

require (
	github.com/360EntSecGroup-Skylar/excelize/v2 v2.3.1
	github.com/gin-gonic/gin v1.6.3
	github.com/jinzhu/gorm v1.9.16 // indirect
	gorm.io/driver/mysql v1.0.1
	gorm.io/gorm v1.20.6
)

你可能感兴趣的:(用go做web开发,go,golang,excel,mysql,web)