每次运行都会更新Python Excel程序

时间:2019-10-05 03:24:45

标签: python excel

我有这个简单的代码,它创建了一个文件“ example.xlsx” 我只需要A1电池在第一次运行时就具有输出。

这是我的初始代码

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)

第一个输出是一个excel文件example.xlsx。每次运行程序时,我都需要更新相同的excel文件。例。

第一次运行只有A1,其网站http://ip.42.pl/raw的输出,每次运行都会将以下内容输入到A2,A3等。

谢谢。我是初学者。请和我一起负担

2 个答案:

答案 0 :(得分:0)

我修改了代码,现在我认为它可以满足您的要求:

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')

检查问题xlsx and xlsm files return badzipfile: file is not a zip file,以弄清为什么必须从excel创建一个空文件,以便openpyxl可以使用它(在else:语句中的行)。

答案 1 :(得分:0)

您可以在openpyxl中使用sheet.max_row来获取长度。像这样:

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)