【问题标题】:Converting empty types to strings from an XLS row将空类型从 XLS 行转换为字符串
【发布时间】: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


    【解决方案1】:

    我是这样做的:

    import xlrd
    import json
    import datetime
    
    book = xlrd.open_workbook("loan Depot Daily Leads.xlsx")
    sh = book.sheet_by_index(0)
    
    rows = []
    for rx in range(sh.nrows):
      row = sh.row(rx)
      items = []
      for cx, cell in enumerate(row):
        if sh.cell_type(rx, cx) == xlrd.XL_CELL_DATE:
          # This turns xlrd.xldate's float representation into 
          # JSON-parseable string
          py_date = xlrd.xldate.xldate_as_datetime(cell.value, book.datemode)
          items.append(str(py_date)) 
        elif cell.value == None:
          # NoneType will error out if you try to stringify it;
          # appending empty string instead
          items.append('')
        else:
          items.append(cell.value)
      rows.append(items)
    with open("leads.txt", "a+") as leadsfile:
      leadsfile.write(json.dumps(rows))
    

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 1970-01-01
      • 2010-10-20
      • 2020-05-21
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多