Skip to main content
 首页 » 编程设计

Golang解析CSV文件

2022年07月19日131dyllove98

Golang解析CSV文件

日常工作实用CSV类型文件很普遍,而且很容易从其他数据源中获得。如Google Sheets,Microsoft Excel,或关系型数据库。如何在应用中加载并解析CSV呢,本文带你实用Golang解析csv文件。

1. 概述

通常其他语言处理CSV文件比较麻烦,通常需要通过第三方库,解析工作量较大。Golang中内置了encoding/csv包,让解析工作变得很简单。

假设我们的数据结构为:姓名、年龄、省份、城市

张勇,24,江苏,南京 
李婉,23,山东,济南 
张飞,33,, 

上面数据表示一组人信息。包括多行、列,我们的任务是加载数据并生成json类型数据。

2. 代码实现

package main 
 
import ( 
	"bufio" 
	"encoding/csv" 
	"encoding/json" 
	"fmt" 
	"io" 
	"log" 
	"os" 
	"strconv" 
) 
 
type Person struct { 
	Name string   `json:"name"` 
	Age  int     `json:"age"` 
	Address   *Address `json:"address,omitempty"` 
} 
 
type Address struct { 
	State string `json:"state"` 
	City  string `json:"city"` 
} 
 
func main() { 
	csvFile, _ := os.Open("person.csv") 
	reader := csv.NewReader(bufio.NewReader(csvFile)) 
	var people []Person 
	for { 
		line, error := reader.Read() 
		if error == io.EOF { 
			break 
		} else if error != nil { 
			log.Fatal(error) 
		} 
		people = append(people, Person{ 
			Name: line[0], 
			Address: &Address{ 
				State:  line[2], 
				City: line[3], 
			}, 
		}) 
 
		people[len(people)-1].Age,_ = strconv.Atoi(line[1]) 
	} 
	peopleJson, _ := json.Marshal(people) 
	fmt.Println(string(peopleJson)) 
} 

上面示例为了简化,都忽略了错误检查。首先打开文件,然后通过缓冲读取文件,循环读每行,生成Person类型数组people,最后利用json.Marshal()方法生成json。

运行上述示例,输出结果为:

[{"firstname":"Nic","lastname":"Raboy","address":{"city":"San Francisco","state":"CA"}},{"firstname":"Maria","lastname":"Raboy", 
"address":{"city":"Dublin","state":"CA"}},{"firstname":"Steve","lastname":"","address":{"city":"","state":""}}] 

3. 总结

本文介绍Golang加载csv文件并解析成数组。每次思绪中都会蹦出简洁,确实Golang有点迷人。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/106181475
阅读延展