【问题标题】:How to read from an excel sheet using pythons xlrd module如何使用 pythons xlrd 模块从 excel 表中读取
【发布时间】:2016-10-11 20:38:03
【问题描述】:

我有以下代码。我想做的是对网站进行屏幕截图,然后将数据写入 Excel 工作表。我无法从 excel 文件中读取现有数据。

import xlwt
import xlrd
from xlutils.copy import copy
from datetime import datetime
import urllib.request
from bs4 import BeautifulSoup
import re
import time
import os  
links= open('links.txt', encoding='utf-8')
#excel workbook
if os.path.isfile('./TestSheet.xls'):
    rbook=xlrd.open_workbook('TestSheet.xls',formatting_info=True)
    book=copy(rbook)
else:
    book = xlwt.Workbook()

try:
    book.add_sheet("wayanad")
except:
    print("sheet exists")
    sheet=book.get_sheet(1)

for line in links:
    print("Currently Scanning\n","\n=================\n",line.rstrip())
    url=str(line.rstrip())    
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    html = urllib.request.urlopen(req)
    soup = BeautifulSoup(html,"html.parser")
    #print(soup.prettify())
    title=soup.find('h1').get_text()    
    data=[]
    for i in soup.find_all('p'):
       data.append(i.get_text())
    quick_descr=data[1].strip()
    category=data[2].strip()
    tags=data[3].strip()
    owner=data[4].strip()
    website=data[6].strip()
    full_description=data[7]
    address=re.sub('\s+', ' ', soup.find('h3').get_text()).strip()
    city=soup.find(attrs={"itemprop": "addressRegion"}).get_text().strip()
    postcode=soup.find(attrs={"itemprop": "postalCode"}).get_text().strip()
    phone=[]
    result=soup.findAll('h4')
    for h in result:
        if h.has_attr('itemprop'):
            phone.append(re.sub("\D", "", h.get_text()))

    #writing data to excel
    row=sheet.last_used_row
    column_count=sheet.ncols()    
    book.save("Testsheet.xls")
    time.sleep(2)           

代码解释

  • 我有一个链接文件,有很多链接一行一行。因此,选择一行 (URL) 并转到该 URL 并抓取数据。
  • 打开一个 Excel 工作簿并切换到用于写入数据的工作表。
  • 将数据附加到 Excel 工作表。->>

execl sheet 结构截图

当前列表为空。但我想从最后一行继续。 我无法从单元格中读取数据。 documentation sayssheet.ncols 可用于计算列数。但是会报错

>>>column_count=sheet.ncols()
>>>AttributeError: 'Worksheet' object has no attribute 'ncols'

我想要的是一种计算行和列的方法,并从单元格中读取数据。许多turials是旧的。现在我正在使用 python 3.4。我已经浏览了这个链接和许多其他链接。但没有运气

Stack overflow

Stackoverdlow

【问题讨论】:

    标签: python excel xlrd xlwt


    【解决方案1】:

    这就是你要找的吗?遍历所有列?

    xl_workbook = xlrd.open_workbook
    
    num_cols = xl_sheet.ncols
    for row_idx in range(0, xl_sheet.nrows):
    

    【讨论】:

    • 正如您在代码中看到的,我有一个名为sheet 的工作表。但是sheet.nrows 抛出错误,即工作表没有此属性。>>> sheet.nrows Traceback (most recent call last): File "<pyshell#125>", line 1, in <module> sheet.nrows AttributeError: 'Worksheet' object has no attribute 'nrows' >>>
    • 上次对我来说效果很好:xl_workbook = xlrd.open_workbook(r".xlsx")sheet_names = xl_workbook.sheet_names()xl_sheet = xl_workbook.sheet_by_name(sheet_names[0])num_cols = xl_sheet.ncolsfor row_idx in range(0, xl_sheet.nrows):
    • 是的,即使您的回答不正确,您的评论也给了我这个想法。如果我想从工作表中读取数据。工作表需要是xlrd 对象,但在我的情况下(sheet 对象)是xlwt 对象。谢谢
    • 帮了大忙 :)
    猜你喜欢
    • 2020-09-15
    • 2021-05-03
    • 2020-08-15
    • 2012-09-24
    • 2020-12-27
    • 2012-05-14
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多