Reputation: 4657
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?
Upvotes: 1
Views: 2322
Reputation: 90929
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
Upvotes: 2