繁体   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