python使用pandas实现dict与excel文件互转

一. dict 转 excel

import pandas as pd

# data=[{'sku': '12001-0026', price: 166}, {'sku': '12001-0027', price: 166}]
# rule = {'sku': '款号', 'price': '价格'}
def dict2Xls(data, rule):
	downFile = 'static/xls/'+datetime.datetime.now().strftime("H%M%S")+'.xlsx'
  	file_path = pd.ExcelWriter(downFile)	

  	orders = list(rule.keys())		# excel中列的顺序

  	pf = pd.DataFrame(data)
  	pf = pf[orders]
    pf.rename(columns = rule, inplace = True)
    pf.to_excel(file_path, sheet_name='sheet1', encoding = 'utf-8',index = False)

	file_path.save()
    file_path.close()

二. excel 转 dict

import pandas as pd

# rule = {'款号': 'sku', '价格': 'price'}
def xls2Dict(path_file, rule):
	df = pd.read_excel(path_file, sheet_name="Sheet1")
	df = df.rename(columns = rule)
	data_dict = df.to_dict(orient='records')  
	return data_dict

你可能感兴趣的:(python,python,pandas,excel)