[英]How to read the same data from excel sheet to the textfile in Python
This code actually is working fine but the output showing is different because the excel sheet were present in some values like int, float but after running the script the output showing like given below. 这段代码实际上运行良好,但是输出显示却有所不同,因为excel工作表以int,float之类的值存在,但是运行脚本后,输出显示如下。 I dont need .0 with that value.
我不需要.0这个值。 I want exact values which is there in input.
我想要输入中存在的确切值。
Rows Column 2 6
a cd 21
b cd 11 4
c cd 22 3
s cd 4.1 2
e cd 4 1
This is the code which showing some wrong value 这是显示一些错误值的代码
import xlrd
import xlwt
workbook=xlrd.open_workbook("xxx.xls")
sh=workbook.sheet_by_index(0)
print sh.nrows
print sh.ncols
n=0
i=0
file=open("xx.txt","w")
for n in range(sh.nrows):
for i in range(sh.ncols):
data =sh.cell_value(n,i)
print data,
file.write(str(data)+" ")
print
file.write("\n")
Please help me for this issue. 请帮我解决这个问题。 I need that whatever it is in excel that should be present in out.
我需要在Excel中显示出来的所有内容。 This is the output for the above code
这是上面代码的输出
Excel treats all numbers as floats . Excel将所有数字视为浮点数 。 So
xlrd
is reading all of them as floats and giving them as it is. 因此,
xlrd
将所有这些读取为浮点数,并按原样提供它们。
A simple workaround for this is to check if a cell
has a float
data type & has no floating value, then convert it to int
type. 一个简单的解决方法是检查
cell
是否具有float
数据类型且没有浮点值,然后将其转换为int
类型。
if isinstance(cell, float) and cell.is_integer():
cell = int(cell)
So, your code becomes, something like this. 这样,您的代码就变成了这样的东西。
import xlrd
workbook = xlrd.open_workbook('data.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows
num_cells = worksheet.ncols
curr_row = -1
with open("xxx.txt", "w") as fh:
for row in range(num_rows):
for column in range(num_cells):
data = worksheet.cell_value(row, column)
if isinstance(data, float) and data.is_integer():
data = int(data)
fh.write(str(data) + " ")
fh.write("\n")
And the output will be: 输出将是:
Rows Column 34.5 6
a cd 54 5
b cd 22.3 4
c cd 56 3
s cd 677.1 2
e cd 32 1
Note: If your input file has floating numbers like 6.0
they will be converted to 6
by default. 注意:如果您的输入文件具有诸如
6.0
浮点数,则默认情况下会将其转换为6
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.