【问题标题】:Transform JSON to excel table将 JSON 转换为 Excel 表格
【发布时间】:2019-12-12 02:55:03
【问题描述】:

我在 csv 中有数据 - 2 列,第一列包含成员 id,第二列包含键值对中的特征(嵌套在另一个之下)。

我看到在线代码可以转换简单的键值对,但不能像上面显示的那样转换数据

我想将这些数据转换成如下的 excel 表格

【问题讨论】:

  • 我对python很陌生

标签: python-3.x


【解决方案1】:

我是用这个XlsxWriter 包完成的,所以首先你必须通过运行pip install XlsxWriter 命令来安装它。

import csv  # to read csv file
import xlsxwriter  # to write xlxs file
import ast

# you can change this names according to your local ones
csv_file = 'data.csv'
xlsx_file = 'data.xlsx'

# read the csv file and get all the JSON values into data list
data = []
with open(csv_file, 'r') as csvFile:
    # read line by line in csv file
    reader = csv.reader(csvFile)

    # convert every line into list and select the JSON values
    for row in list(reader)[1:]:
        # csv are comma separated, so combine all the necessary
        # part of the json with comma
        json_to_str = ','.join(row[1:])

        # convert it to python dictionary
        str_to_dict = ast.literal_eval(json_to_str)

        # append those completed JSON into the data list
        data.append(str_to_dict)

# define the excel file
workbook = xlsxwriter.Workbook(xlsx_file)

# create a sheet for our work
worksheet = workbook.add_worksheet()

# cell format for merge fields with bold and align center
# letters and design border
merge_format = workbook.add_format({
    'bold': 1,
    'border': 1,
    'align': 'center',
    'valign': 'vcenter'})

# other cell format to design the border
cell_format = workbook.add_format({
    'border': 1,
})

# create the header section dynamically
first_col = 0
last_col = 0
for index, value in enumerate(data[0].items()):
    if isinstance(value[1], dict):
        # this if mean the JSON key has something else
        # other than the single value like dict or list
        last_col += len(value[1].keys())
        worksheet.merge_range(first_row=0,
                              first_col=first_col,
                              last_row=0,
                              last_col=last_col,
                              data=value[0],
                              cell_format=merge_format)
        for k, v in value[1].items():
            # this is for go in deep the value if exist
            worksheet.write(1, first_col, k, merge_format)
            first_col += 1
        first_col = last_col + 1
    else:
        # 'age' has only one value, so this else section
        # is for create normal headers like 'age'
        worksheet.write(1, first_col, value[0], merge_format)
        first_col += 1

# now we know how many columns exist in the
# excel, and set the width to 20
worksheet.set_column(first_col=0, last_col=last_col, width=20)

# filling values to excel file
for index, value in enumerate(data):
    last_col = 0
    for k, v in value.items():
        if isinstance(v, dict):
            # this is for handle values with dictionary
            for k1, v1 in v.items():
                if isinstance(v1, list):
                    # this will capture last 'type' list (['Grass', 'Hardball'])
                    # in the 'conditions'
                    worksheet.write(index + 2, last_col, ', '.join(v1), cell_format)
                else:
                    # just filling other values other than list
                    worksheet.write(index + 2, last_col, v1, cell_format)
                last_col += 1
        else:
            # this is handle single value other than dict or list
            worksheet.write(index + 2, last_col, v, cell_format)
            last_col += 1

# finally close to create the excel file
workbook.close()

我注释掉了大部分行,以便更好地理解并降低复杂性,因为您对 Python 非常陌生。如果您没有得到任何意义,请告诉我,我会尽可能多地解释。另外我使用了enumerate() python Built-in Function。检查这个我直接从原始文档中获得的小例子。这个enumerate() 在对列表中的项目进行编号时很有用。

返回一个枚举对象。 iterable 必须是序列、迭代器或其他支持迭代的对象。 enumerate() 返回的迭代器的 __next__() 方法返回一个元组,其中包含一个计数(从 start 开始,默认为 0)和通过迭代 iterable 获得的值。

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

这是我的 csv 文件,

这是excel文件的最终输出。我刚刚合并了重复的标头值(matchrunsconditions)。

【讨论】:

  • 非常感谢贵霜。我正在尝试理解代码将在明天之前确认
  • 为了尝试理解循环,我为 list(reader)[1:] 中的 row 运行了以下命令:print(row) 我得到以下错误 Traceback(最近一次调用最后一次):文件“C:\Users\user.surname\AppData\Local\Programs\Python\Python37\lib\site-packages\IPython\core\interactiveshell.py”,第 3291 行,在 run_code exec(code_obj, self.user_global_ns, self. user_ns) 文件“”,第 1 行,在 中用于列表中的行(阅读器)[1:]:ValueError:对已关闭文件的 I/O 操作。
  • 我检查了 csv。看起来不错。但是提供了 csv 文件的链接供您参考。顺便说一句,错误是“ValueError:对已关闭文件的 I/O 操作”。这是否提供了任何线索。我相信这些都是初学者的问题。感谢您的帮助drive.google.com/file/d/1wXAOMQgda8n0QvfmwJiuwSejP8l9At20/…
  • 它在您发送的文件中完美运行。仍然需要找出错误。为什么 print(row) 放置错误?无论如何,非常感谢您的回答和支持
  • 打印语句工作正常。将报告后续步骤
猜你喜欢
  • 2021-05-27
  • 2019-08-09
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 2021-02-25
  • 2021-04-23
  • 1970-01-01
相关资源
最近更新 更多