我正在练习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))
的行有问题。有人可以帮忙吗?
答案 0 :(得分:1)
是的,你是对的,以下行是错误的 -
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