Python:AttributeError:' str'对象没有属性' font'

时间:2017-05-24 20:27:46

标签: python excel

我使用以下代码写入excel文件。请指正。 我正在解析这个上下文中的HTML页面。我的目标是找到表格元素并将其写入列。

for row in table.findAll('tr', { "class" : "product-row" }):
col = row.findAll('td')

i=1
Image = col[0].a.img['src']
Name = col[1].a.text
Width = col[3].text

record = (Image,Name,Width)

book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("Sheet 1")

sheet1.write(i, Image, Name, Width)

book.save("trial.xls")

它显示以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-179-1d146cb8794d> in <module>()
     14     sheet1 = book.add_sheet("Sheet 1")
     15 
---> 16     sheet1.write(i, Image, Name, Width)
     17 
     18     book.save("trial.xls")

C:\Users\Santosh\Anaconda3\lib\site-packages\xlwt\Worksheet.py in 
write(self, r, c, label, style)
   1086            :class:`~xlwt.Style.XFStyle` object.
   1087         """
-> 1088         self.row(r).write(c, label, style)
   1089 
   1090     def write_rich_text(self, r, c, rich_text_list, 
style=Style.default_style):

C:\Users\Santosh\Anaconda3\lib\site-packages\xlwt\Row.py in write(self, col, 
label, style)
    233 
    234     def write(self, col, label, style=Style.default_style):
--> 235         self.__adjust_height(style)
    236         self.__adjust_bound_col_idx(col)
    237         style_index = self.__parent_wb.add_style(style)

C:\Users\Santosh\Anaconda3\lib\site-packages\xlwt\Row.py in 
__adjust_height(self, style)
     63 
     64     def __adjust_height(self, style):
---> 65         twips = style.font.height
     66         points = float(twips)/20.0
     67         # Cell height in pixels can be calcuted by following approx. 
formula:

AttributeError: 'str' object has no attribute 'font

1 个答案:

答案 0 :(得分:0)

您没有正确使用.write()方法。提供行索引和列索引,然后提供要写入单元格的数据:

record = (Image, Name, Width)

for col_index, item in enumerate(record):
    sheet1.write(i, col_index, item)