内容简介:http://stackoverflow.com/questions/2739989/reading-numeric-excel-data-as-text-using-xlrd-in-python
我正在使用xlrd读取Excel文件,我想知道是否有办法忽略Excel文件中使用的单元格格式,并将所有数据导入文本?
以下是我正在使用的代码:
import xlrd
xls_file = 'xltest.xls'
xls_workbook = xlrd.open_workbook(xls_file)
xls_sheet = xls_workbook.sheet_by_index(0)
raw_data = [['']*xls_sheet.ncols for _ in range(xls_sheet.nrows)]
raw_str = ''
feild_delim = ','
text_delim = '"'
for rnum in range(xls_sheet.nrows):
for cnum in range(xls_sheet.ncols):
raw_data[rnum][cnum] = str(xls_sheet.cell(rnum,cnum).value)
for rnum in range(len(raw_data)):
for cnum in range(len(raw_data[rnum])):
if (cnum == len(raw_data[rnum]) - 1):
feild_delim = '\n'
else:
feild_delim = ','
raw_str += text_delim + raw_data[rnum][cnum] + text_delim + feild_delim
final_csv = open('FINAL.csv', 'w')
final_csv.write(raw_str)
final_csv.close()
这段代码是有效的,但是有一些字段,如邮政编码,作为数字导入,所以它们具有十进制零后缀.例如,Excel文件中是否有邮政编码’79854′,将导入为’79854.0′.
我已经尝试在这个 xlrd spec 找到一个解决方案,但没有成功.
这是因为Excel中的整数值作为浮点数导入Python.因此,sheet.cell(r,c).value返回一个浮点数.尝试将值转换为整数,但首先要确保这些值是Excel中的整数开头:
cell = sheet.cell(r,c)
cell_value = cell.value
if cell.ctype in (2,3) and int(cell_value) == cell_value:
cell_value = int(cell_value)
这一切都在 xlrd spec .
http://stackoverflow.com/questions/2739989/reading-numeric-excel-data-as-text-using-xlrd-in-python
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 使用vbscript代码从文本文件中读取和写入值
- Java读取Excel并解析文本(并格式化输出)
- js 读取 input[type=file] 内容,直接显示文本 | 图片
- 阿里云数加Max Compute的Java Map Reduce程序读取文本资源及其命令行和IDE运行配置
- Tensorflow数据读取指南
- Python如何读取文件
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Fluent Python
Luciano Ramalho / O'Reilly Media / 2015-8-20 / USD 39.99
Learn how to write idiomatic, effective Python code by leveraging its best features. Python's simplicity quickly lets you become productive with it, but this often means you aren’t using everything th......一起来看看 《Fluent Python》 这本书的介绍吧!