![](/img/trans.png)
[英]How to read data from multiple csv files and write into same sheet of single Excel Sheet in Python
[英]How to read the same data from excel sheet to the textfile in Python
這段代碼實際上運行良好,但是輸出顯示卻有所不同,因為excel工作表以int,float之類的值存在,但是運行腳本后,輸出顯示如下。 我不需要.0這個值。 我想要輸入中存在的確切值。
Rows Column 2 6
a cd 21
b cd 11 4
c cd 22 3
s cd 4.1 2
e cd 4 1
這是顯示一些錯誤值的代碼
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")
請幫我解決這個問題。 我需要在Excel中顯示出來的所有內容。 這是上面代碼的輸出
Excel將所有數字視為浮點數 。 因此, xlrd
將所有這些讀取為浮點數,並按原樣提供它們。
一個簡單的解決方法是檢查cell
是否具有float
數據類型且沒有浮點值,然后將其轉換為int
類型。
if isinstance(cell, float) and cell.is_integer():
cell = int(cell)
這樣,您的代碼就變成了這樣的東西。
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")
輸出將是:
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
注意:如果您的輸入文件具有諸如6.0
浮點數,則默認情況下會將其轉換為6
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.