简体   繁体   中英

How to stop openpyxl - python from clearing my excel file every time I re-run the program?

I wrote a simple program for testing with openpyxl where I simply open the .xlsx file, input data into a certain cell, then close the program and run it again, inputting data in a different cell, but when I open the .xlsx after running the program for the second.

My assumption is that openpyxl clears the entire .xlsx file everytime you open it again, is there a way to avoid this?

Here is my code:

from openpyxl import Workbook

wb = Workbook()

dest_filename = 'teste.xlsx'

ws = wb.active
ws.title = "2017"

Row = int(input('row: '))
Column = int(input('column: '))
data = input('data: ')

ws.cell(row = Row, column = Column).value = data

wb.save(filename = dest_filename)

Here is the .xlsx file after running the program for the first time

Here is the .xlsx file after running the program for the second time

You have not read the excel file at all:

Use this to read the existing workbook:

from openpyxl import Workbook,load_workbook
import os

dest_filename = 'teste.xlsx'

if os.path.isfile(dest_filename):
    wb = load_workbook(filename = dest_filename)
else:
    wb = Workbook()

ws = wb.active
ws.title = "2017"

Row = int(input('row: '))
Column = int(input('column: '))
data = input('data: ')

ws.cell(row = Row, column = Column).value = data

wb.save(filename = dest_filename)

Output:

在此输入图像描述

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