2017-02-06 8 views
2

アマチュア時間:RubyのRoo宝石は馬鹿馬鹿しく、Node.jsで利用できるライブラリはこれらの特定のXLSXファイルを解析できないため、Pythonを使用する必要があります。XLS行から空の型を文字列に変換する

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を使用することができますか?ここで

答えて

0

は、私はそれをやった方法は次のとおりです。

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)) 
関連する問題