Go 语言是一门适合用于编写高效且并发的 Web 应用程序的编程语言,同时也可以使用它进行数据处理和分析。在数据处理和分析过程中,Excel 是一种常用的电子表格软件,很多情况下需要将数据导入到 Excel 中进行分析和处理。在 Go 语言中,可以使用两种不同的 excelize 包来操作 Excel 文件,分别是 xuri/excelize 和 360EntSecGroup-Skylar/excelize。
1./xuri/excelize/v2
xuri/excelize 是一个用于操作 Excel 文件的第三方库,可以通过以下方式导入:- import "/xuri/excelize/v2"
复制代码 xuri/excelize 是 Go 语言社区中最受欢迎的 Excel 文件操作库之一,它提供了丰富的功能,可以用于读取、修改和创建 Excel 文件,包括但不限于以下功能:
- 读取 Excel 文件中的数据
- 修改 Excel 文件中的数据
- 在 Excel 文件中插入图片
- 在 Excel 文件中添加图表
- 在 Excel 文件中设置打印选项
- 对 Excel 文件进行加密
- 提供更多的文件格式支持(例如 CSV、XML)
以下是 xuri/excelize 读取 Excel 文件的示例代码:- package main
- import (
- "fmt"
- "/xuri/excelize/v2"
- )
- func main() {
- file, err := excelize.OpenFile("Book1.xlsx")
- if err != nil {
- fmt.Println(err)
- return
- }
- cells := file.GetRows("Sheet1")
- for _, row := range cells {
- for _, colCell := range row {
- fmt.Print(colCell, "\t")
- }
- fmt.Println()
- }
- }
复制代码 2./360EntSecGroup-Skylar/excelize/v2
360EntSecGroup-Skylar/excelize 是由 360 企业安全组(360 Enterprise Security Group)开发的一个 Excel 文件处理库,可以使用以下方式导入:- import "/360EntSecGroup-Skylar/excelize/v2"
复制代码 相较于 xuri/excelize,360EntSecGroup-Skylar/excelize 提供了更多的功能,包括但不限于以下功能:
- 读取 Excel 文件中的数据
- 修改 Excel 文件中的数据
- 在 Excel 文件中插入图片
- 在 Excel 文件中添加图表
- 在 Excel 文件中设置打印选项
- 对 Excel 文件进行加密
- 提供更多的文件格式支持(例如 CSV、XML)
- 提供更多的单元格格式化选项(例如设置单元格样式、设置单元格宽度和高度)
以下是 360EntSecGroup-Skylar/excelize 读取 Excel 文件的示例代码:- package main
- import (
- "fmt"
- "/360EntSecGroup-Skylar/excelize/v2"
- )
- func main() {
- file, err := excelize.OpenFile("Book1.xlsx")
- if err != nil {
- fmt.Println(err)
- return
- }
- cells := file.GetRows("Sheet1")
- for _, row := range cells {
- for _, colCell := range row {
- fmt.Print(colCell, "\t")
- }
- fmt.Println()
- }
- }
复制代码 实战:- // @description: SharedImport 导入
- // @param {string} filePath
- // @param {int64} commitID
- // @param {http.Header} header
- // @return {*}
- func SharedImport(filePath, fileName string, commitID int64, header http.Header) (int64, error) {
- plog.Info("SharedImport", "processing cpp file with file path specified: %v", filePath)
- f, err := excelize.OpenFile(filePath)
- if err != nil {
- plog.Error("", "%v", err)
- return -1, err
- }
- sheetList := garray.NewStrArrayFrom(f.GetSheetList())
- plog.Info("SharedImport", "share file contains sheet list: %v", sheetList.Slice())
- if sheetList.Contains(sharedbilltype.SHARE_INFOMATION_CN) {
- plog.Info("SharedImport", "processing CN share template, finding key cells with chinese")
- err = ShareCNImport(f, filePath, fileName, commitID, header)
- if err != nil {
- plog.Error("", "%v", err)
- return -1, err
- }
- return commitID, nil
- } else if sheetList.Contains(sharedbilltype.SHARE_INFOMATION_EN) {
- plog.Info("SharedImport", "processing EN share template, finding key cells with english")
- err = ShareENImport(f, filePath, fileName, commitID, header)
- if err != nil {
- plog.Error("", "%v", err)
- return -1, err
- }
- return commitID, nil
- } else {
- msgCN := sharedbilltype.ERR_INVALID_SHARE_TEMPLATE_CN
- msgEN := sharedbilltype.ERR_INVALID_SHARE_TEMPLATE_EN
- overviewMsgCN := sharedbilltype.ERR_OVERVIEW_WRONG_FILE_CN
- overviewMsgEN := sharedbilltype.ERR_OVERVIEW_WRONG_FILE_EN
- plog.Warn("SharedImport", msgCN)
- plog.Warn("SharedImport", msgEN)
- plog.Warn("SharedImport", overviewMsgCN)
- plog.Warn("SharedImport", overviewMsgEN)
- err = sharedbillrdb.SaveTInfShareMainValidate([]*sharedbilltype.TableTInfBillShareMainValidate{
- NewInvalidFormatRecord(filePath, commitID, msgCN, msgEN, 0, "", 0, "", 0, "", header, fileName),
- NewInvalidFormatOverviewRecord(filePath, commitID, 0, 0, overviewMsgCN, overviewMsgEN, header, fileName),
- })
- if err != nil {
- plog.Error("", "%v", err)
- return -1, err
- }
- return commitID, nil
- }
- }
复制代码 3.总结
/xuri/excelize/v2 和 /360EntSecGroup-Skylar/excelize/v2 都是 Golang 中用于操作 Excel 文件的库,它们的区别在于它们是由不同的开发者维护的,它们的功能、性能和使用方式也略有不同。
/xuri/excelize/v2 是由 Xuri 开发的 Excel 文件处理库,它可以读取、写入和编辑 XLSX 格式的 Excel 文件,支持大量的 Excel 功能,如图表、数据透 视表、条件格式等,同时还提供了对 PDF 和 HTML 导出的支持。这个库的使用文档详细,具有良好的可维护性和易用性。
/360EntSecGroup-Skylar/excelize/v2 是由 360 安全团队开发的 Excel 文件处理库,它也可以读取、写入和编辑 XLSX 格式的 Excel 文件,支持大量的 Excel 功能,如公式、图表、数据透 视表、条件格式等,同时还提供了对 CSV、TSV 和 JSON 导出的支持。这个库的使用文档相对较少,但是它具有很好的性能和稳定性。
因此,选择使用哪个 Excel 处理库取决于您的需求和偏好。如果您需要处理较为复杂的 Excel 文件并导出到 PDF 或 HTML 文件中,那么您可以选择 /xuri/excelize/v2;如果您需要快速处理大量的 Excel 文件并导出到 CSV、TSV 或 JSON 文件中,那么您可以选择 /360EntSecGroup-Skylar/excelize/v2。
4.知识延展
golang获取Excel数据更新数据库- package main
- import (
- "bufio"
- "database/sql"
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- _ "github.com/alexbrainman/odbc"
- "github.com/xuri/excelize/v2"
- // "encoding/json"
- // "reflect"
- )
- func main() {
- chuliYuanExecl()
- }
- func chuliYuanExecl() {
- fmt.Println("这个程序会打印输入的内容,输入'exit()' 退出程序!")
- // fmt.Println("请输入内容:")
- input := bufio.NewScanner(os.Stdin)
- for {
- fmt.Println("=================!开始转换!=====================================")
- db, err := sql.Open("odbc", "driver={sql server};server=127.0.0.1;port=1433;uid=xx;pwd=xxx;database=xxx")
- if err != nil {
- fmt.Printf(err.Error())
- }
- fmt.Print("输入文件 >> ")
- input.Scan()
- if strings.Compare(strings.TrimSpace(input.Text()), "") == 0 {
- continue
- }
- if strings.Compare(strings.TrimSpace(input.Text()), "exit()") == 0 {
- os.Exit(0)
- }
- fmt.Println("你输入的文件是:", strings.Replace(strings.Replace(strings.Replace(strings.Replace(input.Text(), "& '", "", 1), "'", "", 1), "”", "", 1), "“", "", 1))
- yuanPath := strings.Replace(strings.Replace(strings.Replace(strings.Replace(input.Text(), "& '", "", 1), "'", "", 1), "”", "", 1), "“", "", 1)
- f, err := excelize.OpenFile(yuanPath)
- if err != nil {
- fmt.Println(err)
- return
- }
- defer func() {
- if err := f.Close(); err != nil {
- fmt.Println(err)
- }
- }()
- fmt.Println("开始加载数据库......")
- var sheel = "Sheet1"
- // 获取 Sheet1 上所有单元格
- rows, err := f.GetRows(sheel)
- if err != nil {
- fmt.Println(err)
- return
- }
- fmt.Println("正在更新数据库请等待......")
- // 获取信息
- for i, _ := range rows {
- // 如果有标题或者表头要跳过
- if i < 1 {
- continue
- }
- // 获取单元格数据
- djbh, err := f.GetCellValue(sheel, "A"+strconv.Itoa(i+1))
- if err != nil {
- fmt.Println(err)
- return
- }
- szdbh, err := f.GetCellValue(sheel, "E"+strconv.Itoa(i+1))
- if err != nil {
- fmt.Println(err)
- return
- }
- bm, err := f.GetCellValue(sheel, "G"+strconv.Itoa(i+1))
- if err != nil {
- fmt.Println(err)
- return
- }
- szdzd, err := f.GetCellValue(sheel, "H"+strconv.Itoa(i+1))
- if err != nil {
- fmt.Println(err)
- return
- }
- djzd, err := f.GetCellValue(sheel, "I"+strconv.Itoa(i+1))
- if err != nil {
- fmt.Println(err)
- return
- }
- if djbh == "" {
- continue
- }
- if szdbh == "" {
- continue
- }
- if bm == "" {
- continue
- }
- if szdzd == "" {
- continue
- }
- if djzd == "" {
- continue
- }
- var (
- CGPHID string
- )
- // 数据库查询
- var whcgphsql = `SELECT
- a.ITEM_BUSINESS_ID
- FROM
- ITEM_PURCHASE a
- LEFT JOIN ITEM b ON a.ITEM_ID= b.ITEM_BUSINESS_ID
- WHERE
- b.ITEM_CODE= '` + djbh + `'`
- dhuserrows, err := db.Query(whcgphsql)
- defer dhuserrows.Close()
- for dhuserrows.Next() {
- err := dhuserrows.Scan(&CGPHID)
- if err != nil {
- fmt.Println(err)
- }
- }
- // 数据库更新
- var xssql = `UPDATE ` + bm + ` SET ` + szdzd + `='` + szdbh + `' WHERE ` + djzd + `='` + CGPHID + `'`
- fmt.Println(xssql)
- x, err := db.Exec(xssql)
- if err != nil {
- fmt.Println("UPDATE failed:", err.Error(), x)
- }
- }
- fmt.Println("--------------------- !转换完成!---------------------------")
- }
- return
- }
复制代码 golang获取excel中的指定列数据
获取golang中指定列数据- func ValueLoc(excel_path, sheet_name string, cols []string) [][]string{
- xlsx, err := excelize.OpenFile(excel_path)
- if err != nil {
- os.Exit(1)
- return
- }
- rows := xlsx.GetRows(sheet_name)
- colIndex := make([]int, len(cols))
- // 获取每个col的所在序列号
- for index, row := range rows {
- if index == 0 {
- num := 0
- for _, col := range cols {
- for key, colCell := range row {
- if colCell == col {
- colIndex[num] = key + 1
- num++
- }
- }
- }
- }
- }
- // 对存在的量进行重新矫正,以解决初始变量长度问题
- res_len := 0
- for _, coli := range colIndex {
- if coli-1 >= 0 {
- res_len++
- }
- }
- // 获取数据
- res_data := make([][]string, len(rows)-1)
- res_index := 0
- for index, row := range rows {
- if index != 0 {
- data := make([]string, res_len)
- for i, colindex := range colIndex {
- for key, colCell := range row {
- if key == colindex-1 {
- data[i] = colCell
- }
- }
- }
- res_data[res_index] = data
- res_index++
- }
- }
- return res_data
- }
复制代码 到此这篇关于golang实现读取excel数据并导入数据库的文章就介绍到这了,更多相关go读取excel数据导入数据库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源:互联网
免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作! |
|