1、將excel中的數(shù)據(jù)提取,處理數(shù)據(jù)后保存想要的格式
我們的表格樣式:

image.png
需求:將表格中extend列的數(shù)據(jù)單獨(dú)提取出來(lái),保存為下列樣式的格式

image.png
2、具體代碼實(shí)現(xiàn):
#coding:utf-8
import openpyxl
from pathlib import Path
import json
file = Path(r'H:\02臨時(shí)文件\user.xlsx')
#讀取文件
wb = openpyxl.load_workbook(file)
#判斷是否存在tab
if '結(jié)果' in wb.sheetnames:
pass
else:
wb.create_sheet('結(jié)果',index=1)
#新建tab保存處理的結(jié)果數(shù)據(jù)
ws_n = wb['結(jié)果']
ws_n.append(['classId','name','imageUrl'])
ws = wb.active
#讀取將要修改的那一列數(shù)據(jù)
for i in range(1,ws.max_row):
text = ws.cell(row = i+1,column=2).value
if text !='':
text = json.loads(text)
#extend列是個(gè)字典,提取value數(shù)據(jù)
classId = text['classId']
name = text['name']
imageUrl = text['imageUrl']
#將具體數(shù)據(jù)存入表格中
ws_n.append([classId,name,imageUrl])
#將表格保存
wb.save(file)
說(shuō)明:
1、本次代碼中主要用到openpyxl 這個(gè)庫(kù),讀取數(shù)據(jù),修改數(shù)據(jù),保存數(shù)據(jù)
2、pathlib庫(kù)讀取本地路徑相對(duì)簡(jiǎn)單,推薦大家使用
3、這次只是處理簡(jiǎn)單的數(shù)據(jù),對(duì)于處理結(jié)構(gòu)復(fù)雜數(shù)據(jù)可以借鑒這個(gè)方式做處理