美文网首页
Python Excel to Json

Python Excel to Json

作者: dragon海鸟 | 来源:发表于2020-07-17 00:04 被阅读0次
# -*- coding:utf-8 -*-
import xlrd
import json
import collections

def red_excel(ex_file, index):
    # 获取文档
    wp = xlrd.open_workbook(ex_file)
    file_dic = collections.OrderedDict()
    # 遍历sheets
    for sheetname in wp.sheet_names():
        print(sheetname)
        sheet = wp.sheet_by_name(sheetname)
        dic = collections.OrderedDict()
        for row in range(1, sheet.nrows):
            if sheet.cell_value(row, 0):
                # 按单元格取值
                dic[sheet.cell_value(row, 0)] = sheet.cell_value(row, index)
        file_dic[sheetname] = dic
    # ensure_ascii=False 解决中文乱码
    # indent=4 缩进(一般4或者2)
    # sort_keys=True 按键排序
    json_str = json.dumps(file_dic, ensure_ascii=False, indent=4, sort_keys=True)
    return json_str


def write_fine(doc, str):
    file = open(doc, mode="w+", encoding="utf8")
    file.write(str)
    file.close()

相关文章

网友评论

      本文标题:Python Excel to Json

      本文链接:https://www.haomeiwen.com/subject/bnuvhktx.html