簡體   English   中英

使用xlwt僅將單元格值的文本寫入xls文件

[英]write only the text of cell value to xls file by using xlwt

我正在自己練習Python,並且想從一個xlsx文件中讀取標題行,並以完全相同的方式將其寫入新文件中。 輸入文件標題行的外觀如下: 輸入文件

現在,這是我的輸出文件的樣子: 輸出文件

這是我的代碼:

import xlrd # to read xlsx file
import xlwt # to write new xlsx file

fileName1 = '06082015.xlsx'
f1WorkBook = xlrd.open_workbook(fileName1)

#check sheet names
sheetName = f1WorkBook.sheet_names()
# select the first sheet
f1Sheet1 = f1WorkBook.sheet_by_index(0)
#copy and paste the header lines, row 0 to 17 
header = [f1Sheet1.row(r) for r in range(18)]
#header = [f1Sheet1.cell_value(row, col) for col in range(2) for row in range(18)]
print header[0]


# write header
newWorkBook = xlwt.Workbook()
newsheet = newWorkBook.add_sheet(sheetName[0])

for rowIndex, rowValue in enumerate(header):
    for colIndex, cellValue in enumerate(rowValue):
        newsheet.write(rowIndex, colIndex, str(cellValue))
        print rowIndex
        print colIndex
        print cellValue


newWorkBook.save('processed_'+fileName1[0:8]+'.xls')

我認為newsheet.write(rowIndex, colIndex, str(cellValue)) 有人可以幫忙嗎?

是的,您是正確的,以下一行是錯誤的-

newsheet.write(rowIndex, colIndex, str(cellValue))

這會將您在迭代中獲取的單元格對象直接轉換為字符串,而不是如何獲取其值。 要獲取值,您需要使用cell.value 范例-

for rowIndex, rowValue in enumerate(header):
    for colIndex, cellObj in enumerate(rowValue):
        newsheet.write(rowIndex, colIndex, str(cellObj.value))
        print rowIndex
        print colIndex
        print cellObj.value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM