cant change font on openpyxl - python

i am trying to make an automated xlsx document creator, for this i want to make some of the cells to have bold font, this is part of the code i use
from openpyxl import load_workbook
from openpyxl.styles import Font
from openpyxl.styles.colors import Color
wb_orden = load_workbook(filename = 'resg.xlsx')
ws_orden = wb_orden["Resguardo"]
italic24Font = Font( size = 24, italic = True, bold = True)
ws_orden['A6'] = "hsadgfagahgafdhg"
ws_orden['A6'].font = italic24Font
NAME = "generated/"+"res_"+order+".xlsx"
wb_orden.save(filename = NAME)
but when i see the xlsx file the A6 cell is changed to hsadgfagahgafdhg, but it isn't bold. thanks for reading i hope you can help me whit this
i also tried this but still not working
ws_orden['A6'].font = Font(size=23, underline='single', color='FFBB00', bold=True, italic=True)

Related

Why does python-docx ignore rlt = true?

I need to write into a docx file from python (which i'm a bit new at) but i have to do it written rtl. After days of googling, the best I could do is this:
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT as WD_STYLE_TYPE
from docx.shared import Pt
from docx.shared import Inches, Pt
# create docx file
document = Document()
# create paragraph
para = document.add_paragraph()
# create run
run = para.add_run("Hello World")
# create style
mystyle = document.styles.add_style("mystyle", 2)
run.style = mystyle
font = run.font
font.rtl = True # SET RIGHT TO LEFT
document.save(r"C:\Users\USER\Desktop\Code\TofesEfes\WordTes.docx")
the problem is that for some reason the code just ignores this line:
font.rtl = True # SET RIGHT TO LEFT
If I try to change it to:
font.bold = True # SET FONT TO BOLD
the font will come out bold.
I also tried changing the text to be in a rtl languge and nothin changed.
Does anyone here have any idea why it's doing this?

Openpyxl is unable to read after modifying

Requirement :
1.create a gui using Tkinter
2.Update the excel by fetching values from Tkinter entry widget
3.Read another sheet of the same workbook
4.plot graph using inside the Tkinter window.
Problem: All the functionality is working fine, except when modifying and reading one after another at same time.
Loaded the work book with data_only=False to preserve formulas. I have modified the excel successfully in "INPUT" sheet.Then when I am reading the cells from "SIMULATION" sheets which are linked to the "Input" sheets with formulas , no data is coming.
Opening the excel file with Excel and closing it ,and now if i run the python program again without the modify functionality, program is able to read cell value and plot graph.
During read functionality of the program workbook is loaded 2nd time using data_only = True to get cell values .
Any suggestions will be very helpful for me.
from tkinter import *
from tkinter import ttk
from openpyxl import load_workbook
import datetime
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class Root(Tk):
f = Figure(figsize=(20,8))
a = f.add_subplot(111)
entryString1=0
entryString2=0
entryString3=0
entryString4=0
entryString5=0
entryString6=0
def __init__(self):
super(Root, self).__init__()
self.title("Python Tkinter Dialog Widget")
self.state("zoomed")
self.frame = ttk.Frame(self,borderwidth=2, relief="solid")
self.frame.pack(side='top',fill=X,padx=10,pady=20)
self.entry()
self.button()
self.canvas = FigureCanvasTkAgg(self.f, self.frame)
self.canvas.get_tk_widget().pack(fill="both",padx=10,pady=20)
self.canvas.draw()
def entry(self):
self.frame2 = ttk.Frame(self)
self.frame2.pack(fill=X,padx=10,pady=20)
self.labelentry1 = ttk.Label(self.frame2,text = "V Past Main begin period: ")
self.labelentry1.pack(fill=X,side='left',anchor=W)
self.entry1 = ttk.Entry(self.frame2)
self.entry1.pack(fill=X,side='left')
self.labelentry2 = ttk.Label(self.frame2,text = " V Past PS begin period: ")
self.labelentry2.pack(fill=X,side='left')
self.entry2 = ttk.Entry(self.frame2)
self.entry2.pack(fill=X,side='left')
self.labelentry3 = ttk.Label(self.frame2,text = " Adv 0% Main: ")
self.labelentry3.pack(fill=X,side='left')
self.entry3 = ttk.Entry(self.frame2)
self.entry3.pack(fill=X,side='left')
self.labelentry4 = ttk.Label(self.frame2,text = " Adv 0% PS: ")
self.labelentry4.pack(fill=X,side='left')
self.entry4 = ttk.Entry(self.frame2)
self.entry4.pack(fill=X,side='left')
self.labelentry5 = ttk.Label(self.frame2,text = " Single premium already paid: ")
self.labelentry5.pack(fill=X,side='left')
self.entry5 = ttk.Entry(self.frame2)
self.entry5.pack(fill=X,side='left')
self.labelentry6 = ttk.Label(self.frame2,text = " Yearly premium already paid: ")
self.labelentry6.pack(fill=X,side='left')
self.entry6 = ttk.Entry(self.frame2)
self.entry6.pack(fill=X,side='left')
def button(self):
self.frame3 = ttk.Frame(self)
self.frame3.pack(side='bottom')
self.labelFrame = ttk.LabelFrame(self.frame3,text = "Regenrate Graph")
self.labelFrame.pack(padx=10)
self.button = ttk.Button(self.labelFrame, text = "Click",command = self.fileDialog)
self.button.pack(padx=10)
def fileDialog(self):
self.entryString1 = self.entry1.get()
self.entryString2 = self.entry2.get()
self.entryString3 = self.entry3.get()
self.entryString4 = self.entry4.get()
self.entryString5 = self.entry5.get()
self.entryString6 = self.entry6.get()
#Load excel file
self.filename = "C:\\Users\\ramit\\Desktop\\Projection V0.3_Shankha .xlsx"
#load excel file to modify
self.work_book = load_workbook (self.filename)
self.sheet = self.work_book['Inputs']
if len(self.entryString1) != 0:
self.sheet.cell(row=4,column=5).value=int(self.entryString1)
if len(self.entryString2) != 0:
self.sheet.cell(row=5,column=5).value=int(self.entryString2)
if len(self.entryString3) != 0:
self.sheet.cell(row=6,column=5).value=int(self.entryString3)
if len(self.entryString4) != 0:
self.sheet.cell(row=7,column=5).value=int(self.entryString4)
if len(self.entryString5) != 0:
self.sheet.cell(row=9,column=5).value=int(self.entryString5)
if len(self.entryString6) != 0:
self.sheet.cell(row=10,column=5).value=int(self.entryString6)
self.work_book.save(self.filename)
self.work_book = None
#load excel file to read
self.work_book = load_workbook (self.filename,data_only=True)
self.sheet_1 = self.work_book['Simulation']
self.x = []
self.y = []
for i in range(10, 17):
self.x.append (self.sheet_1.cell(row=i + 1,column=1).value)
self.y.append (self.sheet_1.cell(row=i + 1,column= 77).value)
self.a.clear()
print(self.x)
print(self.y)
self.a.set_xlabel('Simulation date')
self.a.set_ylabel('Reserve')
self.a.plot(self.x, self.y, color='cyan', label='Projection')
self.canvas.draw()
root = Root()
root.mainloop()
The issue is that openpyxl doesn't evaluate the formula in excel. it will only return the last value saved by excel or 'None' (with data_only=True). The latter is what is happening when you change an input cell and use [cell].value to call the value of the cell with the formula. When you don't change the sheet, you get the value set in excel, which is why your code works when you disable/don't do the input to excel functionality.
Easiest way to around the issue is to use xlwings, this should work the way you intend it to. There are also a few other options. such as directly using windows excel commands to update the sheet then using openpyxl to read but I feel swapping modules is the simpler solution. You may also want to consider bringing the function to the python side of the process and just writing the result to the excel sheet.
how to get formula result in excel using xlwings
import xlwings as xw
sheet = xw.Book(r'C:/path/to/file.xlsx').sheets['sheetname']
result = sheet['X2'].value

xlwings: set foreground text color from Python

I'm using xlwings on a Mac and would like to set the foreground color of text in a cell from Python. I see that range.color will change background color which I could use but it has an additional problem that the cell borders are overwritten by the new BG color.
Is there any way to change foreground text color from Python and/or prevent the cell borders being overwritten by a new BG color?
The new API is :
Range("A1").api.Font.ColorIndex = 3
xlwings is currently still a bit light on stylistic features. However, as described here, you can work around like this on Mac by accessing the underlying appscript object directly:
some_rgb_vale = (22, 22, 200)
xw.Range('A1').xl_range.font_object.color.set(some_rgb_vale)
Update:
Nowadays, this is now natively supported by xlwings including Hex color notation:
import xlwings as xw
book = xw.Book()
sheet = book.sheets[0]
sheet["A1"].value = "Some Text"
sheet["A1"].font.color = "#ff0000"
this worked for me
import xlwings as xw
import sys,os
FN = "test.xlsx"
path = os.path.abspath(os.path.dirname(sys.argv[0]))
fn = path + "/" + FN
wb = xw.Book (fn)
ws = wb.sheets["Tabelle1"]
# set background color
ws["B1"].value = "Field1"
ws["B1"].color = (255,255,204)
# set font to bold
ws["B2"].value = "Field2"
ws.range("B2").api.Font.Bold = True
# set font color to green
# color-index see here
ws["B3"].value = "Field3"
ws.range("B3").api.Font.ColorIndex = 4
This solution is working fine for me.
from xlwings.utils import rgb_to_int
import xlwings as xw
sht.range('A1').api.Font.Color = rgb_to_int((192, 192, 192))

Blank workbook is output with WriteOnlyCell and example from documentation

I am using openpyxl 2.2.6 from the bitbucket repository. I tried the simple example from the documentation
This however produces a blank workbook with a single sheet approproately named "MyTestSheet" . but values in any cell.
What am I missing to get write to a cell to work.
from openpyxl import Workbook
wb = Workbook(optimized_write = True)
ws = wb.create_sheet(title="MyTestSheet")
from openpyxl.writer.dump_worksheet import WriteOnlyCell
from openpyxl.comments import Comment
from openpyxl.styles import Style, Font
cell = WriteOnlyCell(ws, value="hello world")
cell.font = Font(name='Courrier', size=36)
cell.comment = Comment(text="A comment", author="Author's Name")
wb.save("testwr_so.xlsx")
You need to append the cell to the worksheet:
ws.append([cell]) # you must always append a sequence

'Cell' object has no attribute 'styles' when trying to set cell font color

I'm using openpyxl 2.0.5 and python 3.4 and I'm simply trying to set the font color to a cell to red
from openpyxl import Workbook
from openpyxl.styles import Color, Font, Style, colors
wb = Workbook()
ws = wb.active
cell = 'A1'
ws[cell].styles = Style(font=Font(color=Color(colors.RED)))
Traceback (most recent call last): File
"C:/Users/b-rosard/PycharmProjects/Test/test.py", line 12, in
ws[cell].styles = Style(font=Font(color=Color(colors.RED)))
AttributeError: 'Cell' object has no attribute 'styles'
I was following the example here: http://openpyxl.readthedocs.org/en/latest/styles.html and I have no clue why I'm getting that error
Simple fix after looking at the attributes of Cell.
ws[cell].style = Style(font=Font(color=Color(colors.RED)))
This code worked for me. I am using python 3.x.
from openpyxl.styles import Color, Font, PatternFill
book = Workbook()
output = book.active
cell = output.cell(row = some value, column = some value)
cell.fill = cell.fill.copy(patternType = 'solid', fgColor = 'FFFFFF00')
'FFFFFF00' used for yellow

Categories