简体   繁体   English

在Python中将xls转换为json

[英]convert xls to json in python

I am trying to convert xls to json and but when I am executing the code it's not giving me the data inside xls sheet, it's only giving me the json structure. 我正在尝试将xls转换为json,但是当我执行代码时,它并没有给我xls工作表中的数据,而只是给了我json结构。 Below is the code which I am running, I am not able to understand what modification I should further make in this so that I can get a perfect json file. 下面是我正在运行的代码,我无法理解我应该对此进行进一步的修改,以便获得一个完美的json文件。

Please note - input is in the form of binary stream and output is also in the form of a stream and not file. 请注意-输入采用二进制流的形式,而输出也采用流而不是文件的形式。

    #!/usr/bin/python -u
import sys
import xlrd
import simplejson
from collections import OrderedDict

wb = xlrd.open_workbook(file_contents=sys.stdin.read())

for sheet_index in range(wb.nsheets):
#       print sheet_index
        sh =  wb.sheet_by_index(sheet_index)
       # print "Processing sheet no ", sheet_index
        attributes = sh.row_values(0)
        #print attributes
        rows_list = []
        attr_list = []
       # print attr_list[0]

        for rownum in range(1,sh.nrows):
                row_val_list = sh.row_values(rownum)
                row_dict = OrderedDict()
                for index in range(len(attr_list)):
                        row_dict[attr_list[index]] = row_val_list[index]

                #row_dict['ID'] = row_val_list[0]
                #row_dict['Name'] = row_val_list[1]

                #rows_list.append(row_dict)

        #json_data = simplejson.dumps(rows_list)
        #sys.stdout.write(json_data)
                rows_list.append(row_dict)
                json_data = simplejson.dumps(rows_list)
                sys.stdout.write(json_data)

#       json_data = simplejson.dumps(rows_list)

        #sys.stdout.write(json_data)
~

Any help is much appreciated 任何帮助深表感谢

here is the correct working python code 这是正确的工作python代码

#!/usr/bin/python -u
import sys
import xlrd
import simplejson
from collections import OrderedDict

wb = xlrd.open_workbook(file_contents=sys.stdin.read())

#print "Sheets are .... ", wb.nsheets

for sheet_index in range(wb.nsheets):
        sh =  wb.sheet_by_index(sheet_index)

        if sh.nrows == 0:
                continue

        attr_list = sh.row_values(0)

        rows_list = []

        for rownum in range(1,sh.nrows):
                row_values = sh.row_values(rownum)
                 row_dict = OrderedDict()

                for index in range(len(attr_list)):
                        row_dict[attr_list[index]] = row_values[index]



                rows_list.append(row_dict)

        json_data = simplejson.dumps(rows_list)
        sys.stdout.write(json_data)

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

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