Printing the value of a formula with openpyxl - excel

I have been trying to research this for the past 2 days and the most regular answer I see is to use data_only=True however that does not seem to fix the issue of printing the value of a formula. Here is my scrip. Does anyone have an answer for this?
import os
import openpyxl
from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook
from openpyxl import load_workbook
import csv
directoryPath = r'c:\users\username\documents\reporting\export\q3'
os.chdir(directoryPath)
folder_list = os.listdir(directoryPath)
for folders, sub_folders, file in os.walk(directoryPath):
for name in file:
if name.startswith("BEA"):
filename = os.path.join(folders, name)
print filename
wb = load_workbook(filename, data_only=True)
sheet = wb.get_sheet_by_name("Sensor Status")
for row_cells in sheet.iter_rows(min_row=1, max_row=4, min_col=8, max_col=13):
for cell in row_cells:
print cell.internal_value

Related

PysimpleGUI Combo source from Excel

Dears,
I'm using excel file as my data source, and in my program I'm using sg.combo , where it contains a long list, consequently, I want to have this list in one of the sheets in my excel file, how to do that ?
from pathlib import Path
import PySimpleGUI as sg
import pandas as pd
current_dir = Path(__file__).parent if '__file__' in locals() else Path.cwd()
EXCEL_FILE = current_dir / 'Example.xlsx'
df = pd.read_excel(EXCEL_FILE)
Thanks

openpyxl ValueError formatting new rows of data

The following code works great the first time I run it (when it creates a new spreadsheet).
When I try to run it again (update existing sheet) to add more data (additional rows) I get the following error
Traceback (most recent call last):
File "C:/PythonPrograms/Workout Program/test_excel_format.py", line 35, in
cell.style = wdata
File "C:\Users\Mark\AppData\Local\Programs\Python\Python37\lib\site-packages\openpyxl\styles\named_styles.py", line 193, in append
raise ValueError("""Style {0} exists already""".format(style.name))
ValueError: Style wdata exists already
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl import load_workbook
from openpyxl.styles import Font, Color, Alignment, Border, Side, colors
from openpyxl.styles import NamedStyle
from datetime import date
from os import path
filename = "format_wb_test.xlsx"
if path.exists(filename):
workbook = load_workbook(filename)
else:
workbook = Workbook()
sheet = workbook.active
tdate = date.today()
data = [tdate, "Data 1", "Data 2", "Data 3"]
wdata = NamedStyle(name="wdata")
wdata.font = Font(bold=True)
wdata.alignment = Alignment(horizontal="center", vertical="center")
for x in range(1, 3):
sheet.append(data) # appends the data to the first empty row.
print("current row: ", sheet._current_row)
ucell = "A" + str(sheet._current_row)
wdata_row = sheet[sheet._current_row]
for cell in wdata_row:
cell.style = wdata
sheet[ucell] = tdate
workbook.save(filename=filename)
I want to be able to add new rows of formatted data esch time I run this code.
I don't see any way to use a NamedStyle to update the format for rows added to an existing
workbook/sheet. If you define the NamedStyle you get the "Already Exists" error. If you don't then you get an error that the "NamedStyle is not defined". The doc states pretty much verbatim what Charlie Clark said in his comment above, "Styles registered automatically on their first use and can then be referenced by name." It does not elaborate or show examples of how to use an existing NamedStyle. Given this I gave up trying to use a NamedStyle and updated the code as follows to make it work. If there is a way to do this with NamedStyle I'd love to see it.
Here's the updated code.
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl import load_workbook
from openpyxl.styles import Font, Color, Alignment, Border, Side, colors
from openpyxl.styles import NamedStyle
from datetime import date
from os import path
filename = "format_wb_test.xlsx"
if path.exists(filename):
workbook = load_workbook(filename)
else:
workbook = Workbook()
sheet = workbook.active
tdate = date.today()
data = [tdate, "Data 1", "Data 2", "Data 3"]
# wdata = NamedStyle(name="wdata")
# wdata.font = Font(bold=True)
# wdata.alignment = Alignment(horizontal="center", vertical="center")
for x in range(1, 3):
sheet.append(data) # appends the data to the first empty row.
print("current row: ", sheet._current_row)
ucell = "A" + str(sheet._current_row)
wdata_row = sheet[sheet._current_row]
for cell in wdata_row:
#cell.style = wdata
sheet[str(cell.coordinate)].font = Font(bold=True)
sheet[str(cell.coordinate)].alignment = Alignment \
(horizontal="center", vertical="center")
sheet[ucell] = tdate
workbook.save(filename=filename)

How to reformat the resultant excel sheet after coming multiple excel sheet in Pandas Python

I tried combining multiple sheets of multiple excel into single excel using pandas python but in the end excel sheet,the rows labels are the excel sheet file name,each sheet as column name.I am getting it as messy.
How do I get it in proper format.Here is the code:
import pandas as pd
import os
from openpyxl.workbook import Workbook
os.chdir("C:/Users/w8/PycharmProjects/decorators_exaample/excel_files")
path = "C:/Users/w8/PycharmProjects/decorators_exaample/excel_files"
files = os.listdir(path)
AllFiles = pd.DataFrame()
for f in files:
info = pd.read_excel(f, sheet_name=None)
AllFiles=AllFiles.append(info, ignore_index=True)
writer = pd.ExcelWriter("Final.xlsx")
AllFiles.to_excel(writer)
writer.save()
The final excel looks like this :
enter image description here
you don't actually need the whole os and Workbook part. That could clean your code and ease finding errors. I assume, that path is the path to the folder where all the excel files are stored:
import pandas as pd
import glob
path = "C:\Users\w8\PycharmProjects\decorators_exaample\excel_files"
file_list = glob.glob(path)
df= pd.DataFrame()
for f in file_list :
info = pd.read_excel(f)
df = df.append(info)
df.to_excel('C:\Users\w8\PycharmProjects\decorators_exaample\excel_files\new_filename.xlsx')
should be as easy as that

multiple column style with python openpyxl

I want to specify the style of the columns in the table. If I select only one column as the style, it works, but if I want to specify more than one of the columns. I get this error message: AttributeError: 'tuple' object has no attribute 'style'
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Font, Color, Alignment, Border, Side, colors
from openpyxl.styles import NamedStyle
path = "my xlsx file path"
workbook = load_workbook(path)
sheet = workbook.active
sheet
shetnames_str = workbook.sheetnames
print(shetnames_str)
print(sheet)
dimensions = sheet.dimensions
print("DimenziĆ³: "+dimensions)
selected_sheetname = workbook["Munka1"]
#Style definition
highlight = NamedStyle(name="highlight")
bd = Side(style='thin', color="000000")
highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
for cell in sheet["A:B"]:
print(cell)
cell.style = highlight
workbook.save(filename="moddedxlsx.xlsx")
I modified my code
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Font, Color, Alignment, Border, Side, colors
from openpyxl.styles import NamedStyle
path = "C:\\Users\\Jutasig\\Documents\\python_jegyzetek\\Dev\\Style\\master_xls_style\\szamla.xlsx"
workbook = load_workbook(path)
sheet = workbook.active
sheet
shetnames_str = workbook.sheetnames
print(shetnames_str)
print(sheet)
dimensions = "\""+sheet.dimensions+"\""
print("DimenziĆ³: "+dimensions)
selected_sheetname = workbook["Munka1"]
#Style definition
def set_border(ws, cell_range):
border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'))
rows = ws[cell_range]
for row in rows:
for cell in row:
cell.border = border
set_border(sheet, sheet.dimensions)
workbook.save(filename="moddedxlsx.xlsx")

panda save and read excel in loop

I have a loop where I call a function in which I loop to read an excel, then write and save it. But at the end I only the last result is stored.
As a simple example
for i in range(3):
callfunc(i)
callfunc(i)
panda open excel
for j in range(10:13:1)
write in excel(i,j) in new sheet
save excel
As final result i only get (3,10) (3, 11) (3,12).
It seems when re-opening the excel in the callfunc the excel doesn't get saved but the original excel is kept and I dont get why.
Thank you !
Let's use separate sheet_name:
import pandas as pd
import numpy as np
from openpyxl import load_workbook
path = r"~\Desktop\excelData\data.xlsx"
book = load_workbook(path)
for i in range(3):
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book
df = pd.DataFrame(x3)
df.to_excel(writer, sheet_name = '{}__sheet'.format(i))
writer.save()
writer.close()

Resources