Glenn Anderson
Glenn Anderson

Reputation: 41

Openpyxl xlsx results are appending instead of overwriting

I'm using openpyxl to write results to an excel file. The problem is when I run the script a second time, the results appear underneath the first results instead of overwriting them as I would like. So, currently the first results appear in rows 2-151 and the 2nd results are appended in rows 152-301. I would like the second results to overwrite the first results in rows 2-151.

Anyone know if this possible to fix?

Thanks

from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import openpyxl
from openpyxl import load_workbook

url = 'http://www.tradingview.com/screener'
driver = webdriver.Firefox()
driver.get(url)

# will give a list of all tickers
tickers = driver.find_elements_by_css_selector('a.tv-screener__symbol')

wb = load_workbook('C:/Users/Jake/results.xlsx')
sheet = wb["Sheet2"]

for index in range(len(tickers)):
   row = [tickers[index].text]
   sheet.append(row)

wb.save('C:/Users/Jake/results.xlsx')

Upvotes: 0

Views: 1664

Answers (1)

Nicolò Gasparini
Nicolò Gasparini

Reputation: 2396

Try writing in the cell you want to overwrite with

sheet.cell(row=index, column=1).value = row

If you don't want to write from the first row but start at 2, simply use

sheet.cell(row=index+2, column=1).value = row

Upvotes: 2

Related Questions