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


Posted in Python onJuly 14, 2020

文件内容:

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操作

以上这篇python3 循环读取excel文件并写入json操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
基于python的汉字转GBK码实现代码
Feb 19 Python
centos系统升级python 2.7.3
Jul 03 Python
使用python编写android截屏脚本双击运行即可
Jul 21 Python
Python的Flask框架中使用Flask-SQLAlchemy管理数据库的教程
Jun 14 Python
Python彩色化Linux的命令行终端界面的代码实例分享
Jul 02 Python
python strip() 函数和 split() 函数的详解及实例
Feb 03 Python
python爬虫_微信公众号推送信息爬取的实例
Oct 23 Python
Python实现获取邮箱内容并解析的方法示例
Jun 16 Python
在python环境下运用kafka对数据进行实时传输的方法
Dec 27 Python
利用python画出AUC曲线的实例
Feb 28 Python
python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例
Mar 10 Python
Python语言中的数据类型-序列
Feb 24 Python
Python爬虫实例——scrapy框架爬取拉勾网招聘信息
Jul 14 #Python
Python爬虫爬取新闻资讯案例详解
Jul 14 #Python
Win10下配置tensorflow-gpu的详细教程(无VS2015/2017)
Jul 14 #Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
Jul 14 #Python
python操作微信自动发消息的实现(微信聊天机器人)
Jul 14 #Python
python如何写try语句
Jul 14 #Python
Python操作MySQL数据库的示例代码
Jul 13 #Python
You might like
用PHP读注册表
2006/10/09 PHP
深入了解 register_globals (附register_globals=off 网站打不开的解决方法)
2012/06/27 PHP
PHP中的traits简单使用实例
2015/05/13 PHP
javascript中的继承实例代码
2011/04/27 Javascript
jquery.post用法示例代码
2014/01/03 Javascript
JS获取各种浏览器窗口大小的方法
2014/01/14 Javascript
IE中JS跳转丢失referrer问题的2个解决方法
2014/07/18 Javascript
jQuery中:lt选择器用法实例
2014/12/29 Javascript
jquery中EasyUI使用技巧小结
2015/02/10 Javascript
jQuery中animate的几种用法与注意事项
2016/12/12 Javascript
深入理解Node.js中的进程管理
2017/03/13 Javascript
JavaScript for循环 if判断语句(学习笔记)
2017/10/11 Javascript
js判断传入时间和当前时间大小实例(超简单)
2018/01/11 Javascript
浅谈React组件之性能优化
2018/03/02 Javascript
详解Vue项目编译后部署在非网站根目录的解决方案
2018/04/26 Javascript
原生微信小程序开发中 redux 的使用详解
2021/02/18 Javascript
python集合用法实例分析
2015/05/30 Python
简单了解Python下用于监视文件系统的pyinotify包
2015/11/13 Python
python实现稀疏矩阵示例代码
2017/06/09 Python
在Python程序员面试中被问的最多的10道题
2017/12/05 Python
python生成器,可迭代对象,迭代器区别和联系
2018/02/04 Python
实例详解Python模块decimal
2019/06/26 Python
django的ORM操作 删除和编辑实现详解
2019/07/24 Python
python创建ArcGIS shape文件的实现
2019/12/06 Python
Python中Subprocess的不同函数解析
2019/12/10 Python
python 回溯法模板详解
2020/02/26 Python
python数字类型math库原理解析
2020/03/02 Python
Python分类测试代码实例汇总
2020/07/23 Python
Python通过类的组合模拟街道红绿灯
2020/09/16 Python
Css3+Js制作漂亮时钟(附源码)
2013/04/24 HTML / CSS
娇韵诗法国官网:Clarins法国
2019/01/29 全球购物
和谐社区口号
2014/06/19 职场文书
2014年中班下学期工作总结
2014/12/11 职场文书
大学生就业推荐表自我评价
2015/03/02 职场文书
postgresql 删除重复数据案例详解
2021/08/02 PostgreSQL
一篇文章看懂MySQL主从复制与读写分离
2021/11/07 MySQL