個人excel文件結構:html
學習了xlrd如何操做excel文件、python讀寫txt文件、jason.dumps()轉換dict爲string類型以後,進行了第一次嘗試。python
第一次嘗試: json
import xlrd import json data = xlrd.open_workbook('test.xlsx')#打開excel文件 table = data.sheet_by_name(u'Sheet1')#經過名稱獲取excel表 nrows = table.nrows final_obj={} for i in range(nrows): cur_row = table.row_values(i) first = str(cur_row[0]) if first: final_obj[first] = [] for j in range(1,len(cur_row)): if cur_row[j]: final_obj[first].append(cur_row[j]) final_str = json.dumps(final_obj) print(final_str) file = open('test.txt', 'w') file.write(final_str) file.close()
經過第一次嘗試的代碼獲得了上面的內容(內容其實已經保存在txt裏面,打印在屏幕上是爲了方便查看結果),得出以下結論:app
接下來主要解決問題1:函數
import xlrd import json data = xlrd.open_workbook('test.xlsx')#打開excel文件 table = data.sheet_by_name(u'Sheet1')#經過名稱獲取excel表 nrows = table.nrows final_obj={} for i in range(nrows): cur_row = table.row_values(i) #我已經經過pirnt(cur_row[0])得知excel中的數字得到後爲浮點型,判斷它是否爲浮點型且可以整除 if type(cur_row[0]) == type(1.1) and cur_row[0]%1 == 0: first = str(int(cur_row[0])) else: first = str(cur_row[0]) if first: final_obj[first] = [] for j in range(1,len(cur_row)): if cur_row[j]: if type(cur_row[j]) == type(1.1) and cur_row[j]%1 == 0: cur_value = str(int(cur_row[j])) else: cur_value = str(cur_row[j]) final_obj[first].append(cur_value) final_str = json.dumps(final_obj) print(final_str) file = open('test.txt', 'w') file.write(final_str) file.close()
此次獲得了相對正確的數字,當我修改了個人excel文件內容時:學習
根據測試,判斷我對excel中的得到的浮點數的轉換基本是對的,但也不能保證徹底正確。測試
上面的代碼每次遇到這種數字都須要作判斷,我但願可以定義一個函數,能夠重複用於轉換數據.net
import xlrd import json data = xlrd.open_workbook('test.xlsx')#打開excel文件 table = data.sheet_by_name(u'Sheet1')#經過名稱獲取excel表 nrows = table.nrows final_obj={} for i in range(nrows): cur_row = table.row_values(i) first = toIntString(cur_row[0]) if first: final_obj[first] = [] for j in range(1,len(cur_row)): if cur_row[j]: final_obj[first].append(toIntString(cur_row[j])) final_str = json.dumps(final_obj) print(final_str) file = open('test.txt', 'w') file.write(final_str) file.close() def toIntString(value): result = "" if type(value) == type(1.1) and value%1 == 0: result = str(int(value)) else: result = str(value) return result
顯然是定義函數的代碼寫在了調用函數部分的內容下面形成的,然而人家JavaScript是能夠這麼幹的,不爽!excel
import xlrd import json def toIntString(value): result = "" if type(value) == type(1.1) and value%1 == 0: result = str(int(value)) else: result = str(value) return result data = xlrd.open_workbook('test.xlsx')#打開excel文件 table = data.sheet_by_name(u'Sheet1')#經過名稱獲取excel表 nrows = table.nrows final_obj={} for i in range(nrows): cur_row = table.row_values(i) first = toIntString(cur_row[0]) if first: final_obj[first] = [] for j in range(1,len(cur_row)): if cur_row[j]: final_obj[first].append(toIntString(cur_row[j])) final_str = json.dumps(final_obj) print(final_str) file = open('test.txt', 'w') file.write(final_str) file.close()
成功!code
最後的疑問:
參考: