欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 【golang】go语言读取Excel表格中的数据

【golang】go语言读取Excel表格中的数据

2024/10/24 13:27:47 来源:https://blog.csdn.net/Bel_Ami_n/article/details/139435274  浏览:    关键词:【golang】go语言读取Excel表格中的数据

    • 导入库
    • 基本用法
    • 封装

在Go语言中,可以使用第三方库来读取Excel文件。
常用的库是github.com/tealeg/xlsx,提供了处理Excel文件的功能。

导入库

首先,安装"github.com/tealeg/xlsx"库。可以通过以下命令在终端中安装:

go get github.com/tealeg/xlsx

基本用法

使用以下示例代码来读取Excel文件:

package mainimport ("fmt""github.com/tealeg/xlsx"
)func main() {// 打开Excel文件excelFileName := "path/to/your/excel/file.xlsx"xlFile, err := xlsx.OpenFile(excelFileName)if err != nil {fmt.Printf("Error opening Excel file: %s\n", err)return}// 遍历每个工作表for _, sheet := range xlFile.Sheets {fmt.Printf("Sheet Name: %s\n", sheet.Name)// 遍历每一行for _, row := range sheet.Rows {// 遍历每个单元格for _, cell := range row.Cells {text := cell.String()fmt.Printf("%s\t", text)}fmt.Println()}}
}

确保将"path/to/your/excel/file.xlsx"替换为实际Excel文件的路径。此代码将遍历Excel文件的每个工作表、每一行和每个单元格,并将单元格内容打印到控制台。

封装

把读取Excel的这种常用的模块封装成函数:

// ReadExcelToMap 读取Excel文件并返回一个map
func ReadExcelToMap(excelFileName string) (map[string][]map[string]string, error) {resultMap := make(map[string][]map[string]string)// 打开Excel文件xlFile, err := xlsx.OpenFile(excelFileName)if err != nil {return nil, fmt.Errorf("Error opening Excel file: %s", err)}// 遍历每个工作表for _, sheet := range xlFile.Sheets {sheetMap := []map[string]string{}// 遍历每一行for rowIndex, row := range sheet.Rows {rowMap := make(map[string]string)// 遍历每个单元格for colIndex, cell := range row.Cells {text := cell.String()colLetter := xlsx.ColIndexToLetters(colIndex)rowMap[colLetter] = text}// 使用行号作为键,将该行的map添加到工作表的map中sheetMap = append(sheetMap, rowMap)fmt.Println(fmt.Sprintf("Row%d", rowIndex+1))// sheetMap[fmt.Sprintf("Row%d", rowIndex+1)] = rowMap}// 使用工作表名作为键,将该工作表的map添加到结果map中resultMap[sheet.Name] = sheetMap}return resultMap, nil
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com