- 导入库
- 基本用法
- 封装
在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
}