openpyxl解决字符长度限制

2019-07-17  本文已影响0人  Py_Explorer

附上代码:

# coding=utf-8
import openpyxl
import json
import time

def write_excel():
    datas = readjson()
    wb = openpyxl.Workbook()
    sheet = wb.get_active_sheet()
   # 此代码只实用python2,python3只要把sheet=wb.active就可以
    # 设置A,B,C,D的长度
    sheet.column_dimensions['A'].width = 20
    sheet.column_dimensions['B'].width = 60
    sheet.column_dimensions['C'].width = 20
    sheet.column_dimensions['D'].width = 2000
    # 设置A,B,C,D的名称
    sheet['A1'] = 'app_Name'
    sheet['B1'] = 'app_Url'
    sheet['C1'] = 'app_Shop'
    sheet['D1'] = 'app_Description'
    # 给A,B,C,D分别赋值
    for i in range(len(datas)):
        print datas[i]
        sheet['A' + str(i + 2)] = str(datas[i]['title'])
        sheet['B' + str(i + 2)] = str(datas[i]['url'])
        sheet['C' + str(i + 2)] = str(datas[i]['wrapperName'])
        sheet['D' + str(i + 2)] = str(datas[i]['description'])
    wb.save('excel.xlsx')
# 读取json文件
def readjson():
    filename = time.strftime('%Y-%m-%d') + '_1.json'
    file_object1 = open('data/%s' % filename, 'r')  #文件路径
    s = []
    try:
        while True:
            line = file_object1.readline()
            line = line.replace('\n', '')
            if line == '':
                break
            else:
                data = json.loads(line) # 用json中的load方法,将json串转
换成字典
                s.append(data)#保存所有字典到列表中
    finally:
        return s

if __name__ == '__main__':
    write_excel()
上一篇下一篇

猜你喜欢

热点阅读