【发布时间】:2017-02-06 03:42:47
【问题描述】:
业余时间:我必须使用 Python,因为 Ruby 的 Roo gem 速度非常慢,而且 Node.js 可用的库无法解析这些特定的 XLSX 文件(可能在生成时损坏?)
Python 的 xlrd 速度很快并且能够解析文件,所以我需要将 XLSX 文件的内容作为 JSON 转储到另一个文件中。
文档的前几行包含很多空单元格,通过xlrd,如下所示:
[empty:u'', empty:u'', text:u'loan Depot Daily Leads', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'', empty:u'']
我希望遍历列表并将 JSON 逐行转储到这样的文件中:
import xlrd
import json
book = xlrd.open_workbook("loan Depot Daily Leads.xlsx")
# print("The number of worksheets is {0}".format(book.nsheets))
# print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
# print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
# print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
with open("dumped.json", "a+") as myfile:
for rx in range(sh.nrows):
row = sh.row(rx)
print(row)
print(json.dumps(row))
myfile.write(json.dumps(row))
但是,我收到一个类型错误:TypeError: empty:u'' is not JSON serializable。
有没有办法将空类型转换为空字符串,以便我可以放心使用json?
【问题讨论】:
标签: python json excel list types