繁体   English   中英

在Python中使用XLRD迭代行和列

[英]Iterating rows and columns using XLRD in Python

我正在使用python xlrd模块来解析Excel文件。 这是excel文件的样子:

Title           A   B   C
attribute 1     1   2   3
attribute 2     4   5   6
attribute 3     7   8   9

我想要以下格式的输出:

[
    {
        "name": "A",
        "attribute1": {
            "value": 1
        },
        "attribute2": {
            "value": 4
        },
        "attribute3": {
            "value": 7
        }       
    },
    {
        "name": "B",
        "attribute1": {
            "value": 2
        },
        "attribute2": {
            "value": 5
        },
        "attribute3": {
            "value": 8
        }   
    },
    {
        "name": "C",
        "attribute1": {
            "value": 3
        },
        "attribute2": {
            "value": 6
        },
        "attribute3": {
            "value": 9
        }       
    }       
]

我尝试了以下内容,但无法弄清楚如何以上述格式创建输出。 希望对此有所帮助!

from xlrd import open_workbook

wb = open_workbook('D:\abc_Template.xlsx', 'r')

wb_sheet = wb.sheet_by_index(0)

values = []

for row_idx in range(7, wb_sheet.nrows):
    col_value = []
    rowval = str((wb_sheet.cell(row_idx, 1)))

    for col_idx in range(1, 5):
        if(col_idx != 2 and col_idx != 1):
            cellVal = wb_sheet.cell(row_idx, col_idx)
            cellObj = {rowval: {"value" : cellVal}}
            col_value.append(cellObj)

    values.append(col_value)

print values

range(7,wb_sheet.nrows)range( 1,5)中的迭代器值与输入表的维度不相等。 首先按列然后按行解析数据似乎更容易。 我对下面的解析器有一个代码建议:

from xlrd import open_workbook
import json

wb = open_workbook('abc_Template.xlsx', 'r')

wb_sheet = wb.sheet_by_index(0)

values = []

for col_idx in range(1, wb_sheet.ncols):
    cellObj = {"name": str(wb_sheet.cell(0, col_idx).value)}
    for row_idx in range(1, wb_sheet.nrows):
        attrib = str(wb_sheet.cell(row_idx, 0).value)
        cellObj[str(attrib)] = {"value": int(wb_sheet.cell(row_idx, col_idx).value)}

    values.append(cellObj)

print(json.dumps(values))

OBS:此示例以python版本> 3运行,请确保导入json库并更改.xlsx文件的输入路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM