Home > Software engineering >  Paste the 2 values I get in excel with xlwings
Paste the 2 values I get in excel with xlwings

Time:01-18

I am trying to create a list of shares and to get the price in turn I need to paste it in the cell of B2 and B3 the values. I am not finding the way that they do not overwrite.

import xlwings as xw
import time
#Data Source
import yfinance as yf

wb = xw.Book('EPGB V3.3.2 FE-AB - Python.xlsb')
sht1 = wb.sheets['Dolar']
while True:
    try:
        tickers = ['GGAL','BMA']
        for ticker in tickers:
            ticker_yahoo = yf.Ticker(ticker)
            data = ticker_yahoo.history()
            last_quote = data['Close'].iloc[-1]
            last_quote_decimals = "{:.2f}".format(last_quote)
            print(ticker, last_quote_decimals)
            sht1.range('B1:B3').value = last_quote_decimals
        time.sleep(10)
    except:
        print('Hubo un error al actualizar excel')

Get the list of values and paste it into the excel

CodePudding user response:

You need to write one value [last quote] to one cell.
Change

sht1.range('B1:B3').value = last_quote_decimals

to

sht1.range(f'B{tickers.index(ticker) 2}').value = last_quote_decimals

This sets the cell for writing to one cell, first B2 then B3. For the first ticker the index is 0; 0 2 = 2, combine this with B in an f string for the cell coord 'B2'.
The next ticker index is 1 so 1 2 = 3, again combine with 'B' for the cell coord 'B3'.
Then as you re-iterate after 10 sec the same cells B2 and B3 are overwitten again with the latest ticker value.
import xlwings as xw
import time
#Data Source
import yfinance as yf

wb = xw.Book('EPGB V3.3.2 FE-AB - Python.xlsb')
sht1 = wb.sheets['Dolar']
while True:
    try:
        tickers = ['GGAL','BMA']
        for ticker in tickers:
            ticker_yahoo = yf.Ticker(ticker)
            data = ticker_yahoo.history()
            last_quote = data['Close'].iloc[-1]
            last_quote_decimals = "{:.2f}".format(last_quote)
            print(ticker, last_quote_decimals)
            # sht1.range('B1:B3').value = last_quote_decimals
            sht1.range(f'B{tickers.index(ticker) 2}').value = last_quote_decimals
        time.sleep(10)
    except:
        print('Hubo un error al actualizar excel')
  • Related