簡體   English   中英

如何使用pythons xlrd模塊從Excel工作表中讀取

[英]How to read from an excel sheet using pythons xlrd module

我有以下代碼。 我想做的是屏蔽網站,然后將數據寫到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.ncols可以計算列數。 但這會引發錯誤

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

我想要的是一種計數行和列並從單元格讀取數據的方法。 許多葬禮是古老的。 現在我正在使用python 3.4。 我已經通過這個鏈接和許多其他鏈接。 但是沒有運氣

堆棧溢出

Stackoverdlow

那是您要找的東西嗎? 經歷所有上校?

xl_workbook = xlrd.open_workbook

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM