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")
Related
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
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)
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
Hello friends,
See code, current output and desired output below. What should be added to the code?
I would like to use bokeh in order to color cell values < 2 in green and cells between 2 and 9 in red.
I would like to add filters to each table column.
Sample output:
Desired output:
import pandas as pd
d = {'A': ['A','B','C']}
data = pd.DataFrame(data=d)
data['B']=[7,8,9]
data['C']=[1,2,3]
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, HTMLTemplateFormatter
output_file(r'C:\Users\rbiberma\Desktop\TEMP\data_table.html')
source = ColumnDataSource(data)
column_list = data.columns
columns = [TableColumn(field=col, title=col) for col in column_list]
data_table = DataTable(source=source, columns=columns, width=200, height=100)
show(data_table)
How to set marker color (line, and body of marker) when using XL_CHART_TYPE.LINE_MARKERS?
Tricks like chart.plots[0].series[0].marker.fill.fore_color = pptx.dml.color.RGBColor(0,0,0) don't work
Below an sample of code:
import traceback
import sys
from pptx import Presentation
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
import pptx
from pptx import Presentation
from pptx.util import Cm, Pt
from pptx.enum.text import MSO_ANCHOR,MSO_VERTICAL_ANCHOR, MSO_AUTO_SIZE,PP_ALIGN
from pptx.chart.data import CategoryChartData, ChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.enum.chart import XL_TICK_MARK
from pptx.enum.chart import XL_LEGEND_POSITION
from pptx.dml.chtfmt import ChartFormat
from pptx.dml.line import LineFormat
from pptx.dml.color import ColorFormat, RGBColor
from pptx.enum.dml import MSO_LINE
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])
chart_data = ChartData()
chart_data.categories = ['Q1 Sales', 'Q2 Sales', 'Q3 Sales']
chart_data.add_series('West', (32.2, 28.4, 34.7))
chart_data.add_series('East', (24.3, 30.6, 20.2))
chart_data.add_series('Midwest', (20.4, 18.3, 26.2))
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide.shapes.add_chart(
XL_CHART_TYPE.LINE_MARKERS, x, y, cx, cy, chart_data
).chart
chart.has_legend = True
chart.legend.include_in_layout = False
chart.series[0].smooth = True
chart.plots[0].series[0].marker.style = 8
try:
fill = chart.plots[0].series[0].marker.format.fill
fill.solid()
fill.fore_color = RGBColor(0,0,0)
#chart.plots[0].series[0].marker.format.line.color = RGBColor(255,0,0)
#chart.plots[0].series[1].marker.style = 2
except Exception as error:
traceback.print_exc()
prs.save('chart-01.pptx')
It produces error:
Traceback (most recent call last): File
"", line 38, in
fill.fore_color = RGBColor(0,0,0) AttributeError: can't set attribute
Try:
fill = series.marker.format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(0,0,0)
(Note the .format between marker and fill.)
This sets the color for all markers for the series.
If you want to set the color of individual points, you can use something like:
fill = series.points[0].format.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 0, 0)
The fill.solid() call sets the fill type to solid, which is necessary before assigning to .fore_color, because not all fill types have a .fore_color attribute.