网络编程
位置:首页>> 网络编程>> Python编程>> python3 循环读取excel文件并写入json操作

python3 循环读取excel文件并写入json操作

作者:qubeijun  发布时间:2022-11-07 15:40:11 

标签:python3,excel,json

文件内容:

python3 循环读取excel文件并写入json操作

excel内容:

python3 循环读取excel文件并写入json操作

代码:


import xlrd
import json
import operator

def read_xlsx(filename):
# 打开excel文件
data1 = xlrd.open_workbook(filename)
# 读取第一个工作表
table = data1.sheets()[0]
# 统计行数
n_rows = table.nrows

data = []

# 微信文章属性:wechat_name wechat_id title abstract url time read like number
for v in range(1, n_rows-1):
 # 每一行数据形成一个列表
 values = table.row_values(v)
 # 列表形成字典
 data.append({'wechat_name': values[0],
     'wechat_id': values[1],
     'title':  values[2],
     'abstract': values[3],
     'url':   values[4],
     'time':  values[5],
     'read':  values[6],
     'like':  values[7],
     'number':  values[8],
     })
# 返回所有数据
return data

if __name__ == '__main__':
d = []
# 循环打开每个excel
for i in range(1, 16):
 d1 = read_xlsx('./excel data/'+str(i)+'.xlsx')
 d.extend(d1)

# 微信文章属性
# 按时间升序排列
d = sorted(d, key=operator.itemgetter('time'))
# 写入json文件
with open('article.json', 'w', encoding='utf-8') as f:
 f.write(json.dumps(d, ensure_ascii=False, indent=2))

name = []
# 微信id写文件
f1 = open('wechat_id.txt', 'w')
for i in d:
 if i['wechat_id'] not in name:
  name.append(i['wechat_id'])
 f1.writelines(i['wechat_id'])
 f1.writelines('\n')

print(len(name))

结果:

python3 循环读取excel文件并写入json操作

补充知识:Python mysql数据 读取时间参数 for循环写入Excel文件

最近在利用Python 实现自动化表报时,有个功能是mysql的业务时间是读取模板文件的时间参数,需要用到for循环功能,基本思路是:

1.自动创建一个输出文件的文件夹

2.根据模板文件创建一个新的excel文件到新创建的文件夹中

3.每次写入时返回sheet的最大行数max_row,下次写入时从最大行的下一行开始继续写入

4.每次读取必须为同一个文件

代码如下:


#! /usr/bin/env python
# -*- coding:utf-8 -*-

import MySQLdb
from openpyxl import load_workbook
import sys
import time
import os

reload(sys)
sys.setdefaultencoding('utf8')

# 打开数据库连接
db = MySQLdb.connect(host="localhost", user="zimu", passwd="zimu", db="xxx", port=0000,charset='utf8')

template_file_demo = r"D:\path\demo.xlsx"
# makedirs 创建文件时如果路径不存在会创建这个路径
output_path = r"D:\output\demo"+"_"+ time.strftime("%Y%m%d", time.localtime()) +"_" + str(int(time.time()))+"\\"
os.makedirs(output_path)
#创建文件到新创建的文件夹中
book_demo = load_workbook(template_file_demo)
book_demo.save(output_path + "demo" +"_"+time.strftime("%Y%m%d", time.localtime())+".xlsx")
#读取指定文件夹下的文件
demo_file = output_path+"demo"+"_"+time.strftime("%Y%m%d", time.localtime())+".xlsx"

def savedata(start_time,end_time):
demosql = '''select * from demo where start_date<='%s' and end_date>='%s''''%(start_time,end_time)
 cursor = db.cursor()
 cursor.execute(demosql)
 demodata = cursor.fetchall()

demo_book = load_workbook(demo_file)
 demosheet = demo_book['demo']
 row_t = demosheet.max_row

i = 0
 while i < len(demodata):
   for j in range(0, 8):
     demosheet.cell(row_t + i + 1, j + 1).value = demodata[i][j]
   i += 1
   demo_book.save(output_path+"demo"+"_"+time.strftime("%Y%m%d", time.localtime())+".xlsx")

book_template = load_workbook(template_file_demo)
timet = book_template['时间配置']
for t in range(2, timet.max_row + 1): # 读取配置表中的时间
 savedata(timet.cell(t, 1).value, timet.cell(t, 2).value)

5.模板文件的时间参数设置如下:

python3 循环读取excel文件并写入json操作

来源:https://blog.csdn.net/qubeijun/article/details/81389980

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com