- 導入庫
- 基本用法
- 封裝
在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
}