简体   繁体   English

使用xlwt仅将单元格值的文本写入xls文件

[英]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. 我正在自己练习Python,并且想从一个xlsx文件中读取标题行,并以完全相同的方式将其写入新文件中。 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)) . 我认为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 . 要获取值,您需要使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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