简体   繁体   中英

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

I am practicing Python on my own and would like to read the header lines from one xlsx file and write them in a new file in the exactly the same way. Here's how the input file header lines look like: 输入文件

And here's how my output file look like by now: 输出文件

And here are my codes:

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')

I think something is wrong with the line of newsheet.write(rowIndex, colIndex, str(cellValue)) . Can someone help?

Yes you are correct, the following line is wrong -

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

This directly converts the cell object you get in the iteration to string, that is not how you get its value. To get the value , you need to use cell.value . Example -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM