Python Excel Program Update Every Run - python

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)

Related

How to save transformed file into new excel file using Openpyxl Python?

I have 3 excel files currently in my working directory. All 3 files has name that ends with "_Updated.xlsx". I wanted to transform the files such that all empty rows in each of the files get deleted. I have created function for it, but the only issue is I cannot save all transformed file using below code. Not sure what is wrong ? The reason for creating new file is I would like to save my raw files.
Python code
import openpyxl
import os
from openpyxl import load_workbook,Workbook
import glob
from pathlib import Path
Excel_file_path="/Excel"
for file in Path(Excel_file_path).glob('*_Updated.xlsx'):
wb=load_workbook(file)
wb_modified = False
for sheet in wb.worksheets:
max_row_in_sheet = sheet.max_row
max_col_in_sheet = sheet.max_column
sheet_modified = False
if max_row_in_sheet > 1:
first_nonempty_row = nonempty_row() # Function to find nonempty row
sheet_modified = del_rows_before(first_nonempty_row) #Function to delete nonempty row
wb_modified = wb_modified or sheet_modified
if wb_modified:
for workbook in workbooks:
for sheet in wb.worksheets:
new_wb = Workbook()
ws = new_wb.active
for row_data in sheet.iter_rows():
for row_cell in row_data:
ws[row_cell.coordinate].value = row_cell.value
new_wb.save("/Excel/"+sheet.title+"_Transformed.xlsx")
In case, if any one is still looking for answer to my above question. Below is the code that worked for me.
import openpyxl
import os
from openpyxl import load_workbook
import glob
from pathlib import Path
Excel_file_path="/Excel"
for file in Path(Excel_file_path).glob('*_Updated.xlsx'):
wb=load_workbook(file)
wb_modified = False
for sheet in wb.worksheets:
max_row_in_sheet = sheet.max_row
max_col_in_sheet = sheet.max_column
sheet_modified = False
if max_row_in_sheet > 1:
first_nonempty_row = get_first_nonempty_row() # Function to find nonempty row
sheet_modified = del_rows_before(first_nonempty_row) #Function to delete nonempty roW
file_name = os.path.basename(file)
wb.save("Excel/"+file_name[:-5]+"_Transformed.xlsx")
wb.close()

Python (OpenPyxl) openpyxl not write anything

Code :
wb = Workbook()
sdwbb = load_workbook(sdpath)
filename = os.path.basename(sdpath)
bulan = "September"
try:
sdp = sdwbb[bulan]
except:
sdwbb.create_sheet(bulan)
wb.save(filename)
time.sleep(0.5)
sdp = sdwbb[bulan]
cell_one = sdp['F1']
cell_one.value = 'test'
sdwbb.save(filename)
for your information I doesn't get any error but its doesn't write anything cell f1 sheet September
what I trying to do is to write on specific workbook ,sheet ,and cell
This is my code to write "test" in cel F1 (in the current sheet) in the file test.xlxs in the same folder:
from openpyxl import Workbook, load_workbook
wb = load_workbook("test.xlsx")
ws = wb.active
ws["F1"] = "test"
wb.save("test.xlsx")
print("done")
It's as easy as that :).
Also, you should devenitly check out the documentation of openpyxl: https://openpyxl.readthedocs.io/en/stable/tutorial.html#create-a-workbook

Save data into excel file in Python

I wrote a python code to get a string output as following code segment.
a = "First "
b = "Second"
c = a+b
I need to save value of c in a excel file every time I run that program.How can I do that?
Make first your excel file named test.xlsx
Then use this code to load your file and write to it:
from openpyxl import load_workbook
filename= 'test.xlsx'
wb = load_workbook(filename)
file = wb.active
file.append(["data"])
wb.save(filename=filename)
from openpyxl import Workbook
a = "First "
b = "Second"
c = a+b
file_path= "temp.xlsx"
wb = Workbook()
ws = wb.active
ws.append(c)
wb.save(file_path)

Append data into new excel sheet with openpyxl

I have bunch of excel workbooks and I would like to get cell values from them and write to a new sheet.
My code is not appending new data.It is just overwriting cells with values from last workbook.
(I've changed the pasted code.It was pasted incorrect.)
Here is my code
from openpyxl import load_workbook
booklist = ["17_02.xlsx", "17_03.xlsx",
"17_04.xlsx", "17_05.xlsx",
"17_06.xlsx", "17_08.xlsx",
"17_09.xlsx", "17_10.xlsx"]
for wb in booklist:
book = load_workbook(filename =wb,data_only=True)
report = load_workbook(filename="dest.xlsx", data_only=True)
print(book)
sheet = book['Sheet']
reportsheet=report['First']
row_count=sheet.max_row
column_count=sheet.max_column
for r in range(1,row_count+1):
for c in range(1,column_count+1):
source=sheet.cell(row=r, column=c)
dest = reportsheet.cell(row=r, column=c)
dest.value = source.value
sheet.title = 'First'
book.save("dest.xlsx")
Edit:
After the mickNeill's answer I changed the code and it worked for appending.But now there is another problem.
If I run the code (after clearing the cells) second time or more it's appending the data to the rows after the cleared cells.
First run:
Data appended to A1:A20
Clear the cells,save and close the workbook.
Second run:
Data appended to A21:A20 instead of A1:A20 (cleared cells)
Every time I run the code value of the reportRow continues to increase (1,20,40 ...) and appending data to higher number of rows.
from openpyxl import load_workbook
booklist = ["17_02.xlsx", "17_03.xlsx",
"17_04.xlsx", "17_05.xlsx",
"17_06.xlsx", "17_08.xlsx",
"17_09.xlsx", "17_10.xlsx"]
for wb in booklist:
book = load_workbook(filename =wb,data_only=True)
report = load_workbook(filename="dest.xlsx", data_only=True)
print(book)
sheet = book['Sheet']
reportsheet=report['First']
row_count=sheet.max_row
reportRow = reportsheet.max_row
column_count=sheet.max_column
for r in range(1,row_count+2):
for c in range(1,column_count+1):
source=sheet.cell(row=r, column=c)
dest = reportsheet.cell(row=reportRow, column=c)
dest.value = source.value
reportRow += 1
report.save("dest.xlsx")
Try this: Editied, you are saving the wrong book, last line
from openpyxl import load_workbook
booklist = ["Book5.xlsx", "Book6.xlsx","Book7.xlsx"]
report = load_workbook(filename="dest.xlsx", data_only=True)
for wb in booklist:
book = load_workbook(filename =wb,data_only=True)
#print(book)
sheet = book['Sheet1']
reportsheet=report['First']
row_count=sheet.max_row
reportRow = reportsheet.max_row + 1
print reportRow
column_count=sheet.max_column
for r in range(1,row_count+1):
for c in range(1,column_count+1):
print reportRow
source=sheet.cell(row=r, column=c)
dest = reportsheet.cell(row=reportRow, column=c)
dest.value = source.value
sheet.title = 'First'
reportRow += 1
report.save("dest.xlsx")

Copying image from a worksheet using openpyxl

I have a Python program that creates a new excel file based on some worksheets from a few other files. The following code I have copies the worksheets perfectly, but is unable to copy the image that is present in the worksheet. How do I copy images in an Excel worksheet to another Excel workbook using Python?
path1 = "/mnt/e/RecEasy-MVP-Python/FlaskApp/Uploaded_files/" + key
print path1
path2 = "/mnt/e/RecEasy-MVP-Python/FlaskApp/Compiled/" + current_acc_group + "_" + current_gl_account + ".xlsx"
print path2
path_to_key_sheet = "/mnt/e/RecEasy-MVP-Python/FlaskApp/Uploaded_files/" + key + "_key_sheet.txt"
print "Path to key sheet file:"
print path_to_key_sheet
wb1 = xl.load_workbook(filename=path1, read_only=True, data_only=True)
ws1 = wb1.worksheets[2]
counter = 0
for sheet in wb1:
if (str(sheet.title) == str(content_of_key_sheet_file)):
ws1 = wb1.worksheets[counter]
print "Sheet selected"
print sheet.title
counter = counter + 1
ws2 = wb2.create_sheet(ws1.title)
print "Copying from the Excel file: " + path1
for row in ws1:
for cell in row:
if (cell.value != None):
ws2[cell.coordinate].value = cell.value
wb2.save(path2)
install Pillow (just pip install Pillow, not needed import in your file)
then:
from openpyxl import drawing
.
.
.
img = drawing.image.Image('yourImg.png')
yourSheet.add_image(img, 'A2')
where A2 is your cell
I'd been struggling with this for a bit as most of the libraries I typically use to manipulate xlsx files seemed to not want to support this.
Fortunately, .xlsx is ooxml format. Thus, all you need to do is unzip the .xlsx and locate the pictures in xl/media/ of the directory you extracted your workbook to.
zip = ZipFile('yourWorkbook.xlsx')
zip.extractall()
Now you can insert them back into your new spreadsheet spreadsheet
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')

Categories