1、代码如下:
# -*- coding:utf-8 -*-
import os
import xlwt
import xlrd
import xlutils
from xlutils.copy import copy
import re
def saveBrankExcel():
with open("output1/shangcheCarBrank.txt","r",encoding="utf-8") as fp:
datas = fp.readlines()
count = 1
for i in datas:
dict1 = {}
# 用正则取出需要的保存数据内容
dict1["makename"] = re.findall("'makename': '(.*?)'", i)[0]
dict1["makeid"] = re.findall("'makeid': '(.*?)'", i)[0]
dict1["modelname"] = re.findall("'modelname': '(.*?)'", i)[0]
dict1["modelid"] = re.findall("'modelid': '(.*?)'", i)[0]
dict1["trimname"] = re.findall("'trimname': '(.*?)'", i)[0]
dict1["trimid"] = re.findall("'trimid': '(.*?)'", i)[0]
dict1["price"] = re.findall("'price': '(.*?)'", i)[0]
print(dict1)
saveData(dict1,count)
count = count+1
def saveData(getdata,count):
# 建立文件夹存放Excel文件
folder_name = "output1"
if not os.path.exists(folder_name):
os.mkdir(folder_name)
file_name = "shangcheBrank" + ".xls"
file_path = folder_name + "/" + file_name
if not os.path.exists(file_path):
# 保存xls格式
# 创建一个workbook并设置编码格式
workbook = xlwt.Workbook(encoding="utf-8")
sheet = workbook.add_sheet(u"工作表1")
# 创建行标题内容
header = [u"makename", u"makeid", u"modelname", u"modelid", u"trimname", u"trimid", u"price"]
for index, item in enumerate(header):
# 参数对应为(行,列,值)
sheet.write(0, index, item)
# 保存
workbook.save(file_path)
# 读取一个Excel文件
oldw = xlrd.open_workbook(file_path, formatting_info=True)
# 复制表
neww = copy(oldw)
# neww = xlutils.copy.copy(oldw)
# 定位新的表 使用get_sheet方法
newsheet = neww.get_sheet(0)
print(type(getdata))
lines = [getdata['makename'], getdata['makeid'], getdata['modelname'], getdata['modelid'], getdata['trimname'], getdata['trimid'],getdata['price']]
for i, ite in enumerate(lines):
newsheet.write(count, i, ite)
# 保存
neww.save(file_path)
saveBrankExcel()
2、结果如下: