个人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
最后的疑问:
参考: