1. 程式人生 > >python3 迴圈讀取excel檔案並寫入json

python3 迴圈讀取excel檔案並寫入json

檔案內容:

excel內容:

程式碼:

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))

結果: