简体   繁体   中英

Python Excel Program Update Every Run

I have this simple code and it creates a file "example.xlsx" I only need the A1 Cell to have an output for the first run.

This is my initial code

from openpyxl import Workbook

import requests


workbook = Workbook()
sheet = workbook.active

success= "DONE"
sheet["A1"] = requests.get('http://ip.42.pl/raw').text

workbook.save(filename="example.xlsx")
print(success)

The first output is an excel file example.xlsx. I am required to update the same excel file every time we run the program. Example.

The 1st run has only A1 with the output from the website http://ip.42.pl/raw and the following will be input to A2, A3 and so on every run.

THANK YOU. I AM BEGINNER. PLEASE BEAR WITH ME

I modified the code, and now I think it does what you ask for:

from openpyxl import Workbook, load_workbook
import os
import requests

workbook = Workbook()

filename = "example.xlsx"

success = "DONE"

# First verifies if the file exists
if os.path.exists(filename):
    workbook = load_workbook(filename, read_only=False)
    sheet = workbook.active
    counter = 1
    keep_going = True

    while keep_going:
        cell_id = 'A' + str(counter)
        if sheet[cell_id].value is None:
            sheet[cell_id] = requests.get('http://ip.42.pl/raw').text
            keep_going = False
        else:
            counter += 1

    workbook.save(filename)
    print(success)

else:
    # If file does not exist, you have to create an empty file from excel first
    print('Please create an empty file ' + filename + ' from excel, as it throws error when created from openpyxl')

Check the question xlsx and xlsm files return badzipfile: file is not a zip file for clarification about why you have to create an empty file from excel so openpyxl can work with it (line in the else: statement).

You could use sheet.max_row in openpyxl to get the length. Like so:

from openpyxl import Workbook

import requests


workbook = Workbook()
sheet = workbook.active

max_row = sheet.max_row

success= "DONE"
sheet.cell(row=max_row+1, column=1).value = requests.get('http://ip.42.pl/raw').text
# sheet["A1"] = requests.get('http://ip.42.pl/raw').text

workbook.save(filename="example.xlsx")
print(success)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM