PatternFill issue using Openpyxl on Python. Can anyone help me? - python

I'm trying to change the background color of a cell according to its text using IF and Patternfill from Openpyxl but I'm receiving a type error. See bellow the code:
#Level - Replied Travel Alerts(RTA)
incident_index = item.body.index("incident") + 12
category_indexpos = item.body[incident_index:].index("Category") + incident_index
level = item.body[incident_index:category_indexpos]
ws.cell(row=index+2, column = 2).value = level
if "Advisory" in level:
advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")
ws.cell(row=index+2, column = 2).fill = advisory_pattern
elif "Notice" in level:
notice_pattern = Pattern(patternType = "solid", fgColor = "00B050")
ws.cell(row=index+2, column = 2).fill = notice_pattern
elif "Special" in level:
special_pattern = Pattern(patternType = "solid", fgColor= "FF0000")
ws.cell(row=index+2, column = 2).fill = special_pattern
but I'm getting an error on the "advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")" line. See the message:
Exception has occurred: TypeError
cannot create 're.Pattern' instances
Can anyone help me?
Thanks

Well, re.Pattern is from the python re library, which has nothing to do with creating background fills in Openpyxl
First, I would use this import at the top of your code:
from openpyxl.styles import fills
Then you can modify your lines to fit this format (I used your first fill as my example):
ws.cell(row=index+2, column = 2).fill = fills.PatternFill("solid", fgColor="FFFF00")
If you want to store your fills in variables still, just make sure you are using fill objects from the openpyxl fills library and not Pattern objects from the python re library.

Related

Is there a way to you can copy a range in excel and paste it in a specific slide in powerpoint using python win32/openpyxl/xlsxwriter/pptx

powerpoint_object = win32com.client.Dispatch("Powerpoint.Application")
powerpoint_object.visible = True
powerpoint_presentation = powerpoint_object.Presentations.Open(r"C:\Users\<User>\Desktop\test.pptx")
excel_object = win32com.client.Dispatch("Excel.Application")
excel_object.visible = True
excel_workbook = excel_object.Workbooks.Open(Filename=r"C:\Users\Desktop\X_2022-06-15.xlsx")
excel_worksheet = excel_workbook.Worksheets("Shee1")
excel_range = excel_worksheet.Range("A1:J50")
excel_range.Copy()
powerpoint_slide = powerpoint_presentation.Slides.Add(1,12)
powerpoint_slide.Shapes().Paste()
It is giving me the following error
pywintypes.com_error: (-2147352562, 'Invalid number of parameters.', None, None)
Am I going about this incorrectly or am I missing something? If not by using win32, is there a way to use openpyxl and pptx to do this?

How to define a function to add cell colour for a table that created by python-docx?

I want to define a function to filling header colour,
for now, I am just hard code every object.
Here is the code I used, I tried to define a function to add cell colour.
The error msg shown below:
from docx import Document
from openpyxl import load_workbook
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from zmq import NULL
document = Document()
k=1
for k in range (1,5):
table = document.add_table(rows=2, cols=3)
table.cell(0,0).text = ('Type')
table.cell(0,1).text = ('Value')
table.cell(0,2).text = ('Connections')
def set_table_header_bg_color(table.rows[row_ix].cell):
"""
set background shading for Header Rows
"""
tblCell = cell._tc
tblCellProperties = tc.get_or_add_tcPr()
clShading = OxmlElement('w:shd')
clShading.set(qn('w:fill'), "00519E") #Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
tblCellProperties.append(clShading)
return cell
for each_row in table.rows :
for each_cell in each_row.cells:
set_table_header_bg_color(each_cell)
Could you guys help me to solve this error?
I copy this function from https://stackoverflow.com/a/62079054/18540814
but the function seems cannot use in my case......
Some things to note
You need to be careful of indentation; 'def' should not be indented and don't place it in the middle of a section of code.
There is no need to initialise a variable when assigning to a range; k=1 isn't needed the range is assigned on the next line.
No need to return the 'cell' the def is a function to change the shading on a cell, there is nothing to return.
As you have written it you are creating 3 tables with the 'k' range not sure if that is your intent.
from docx import Document
from docx.oxml.shared import qn
from docx.oxml.xmlchemy import OxmlElement
doc_name = 'doc_w_tables.docx'
document = Document()
tables = document.tables
def set_table_header_bg_color(tc):
"""
set background shading for Header Rows
"""
tblCellProperties = tc._element.tcPr
clShading = OxmlElement('w:shd')
clShading.set(qn('w:fill'), "00519E") # Hex of Dark Blue Shade {R:0x00, G:0x51, B:0x9E}
tblCellProperties.append(clShading)
for k in range(0, 3):
table = document.add_table(rows=2, cols=3)
table.cell(0, 0).text = 'Type'
table.cell(0, 1).text = 'Value'
table.cell(0, 2).text = 'Connections'
for j in range(0,3):
set_table_header_bg_color(table.rows[0].cells[j])
document.save(doc_name)
docx python-docx

When I use the rich library to add colour, why does it affect the symbols around it? Is there a way to stop this from happening?

What am I trying to do?
I am using the rich library to print words out in different colours.
I have come up with the following program to do so:
from rich import print as rprint
rprint('[[green]1[/green]] Create new password')
print('[2] See existing passwords')
print('[3] Exit')
Output:
My Problem
As you can see on the image above, the square brackets which surround 1 are a brighter in color compared to the ones beneath it 2 & 3. Is there a way to make the square brackets all the same color (grey) instead of a white?
Thanks in advance.
Note:
I am aware that this does not hinder how the program works but I like things to be aesthetically pleasing and this is really bugging me for some reason.
Also, I was just testing how I could go about changing colours using rich, but I'm open to suggestions on other ways do this.
Rich performs highlighting on the output, for numbers, strings, data etc. In your example it is highlighting braces, which can be helpful when you print data structures.
You can disable this feature if you construct a Console object and set highlight=False on the print method.
Here's an example:
from rich.console import Console
console = Console()
console.print('[[green]1[/green]] Create new password', highlight=False)
See the docs on highlighting for the details.
As the op is open to other ways, here is my way of doing..
Initiate a class with standard terminal color codes.
class bcolors:
ResetAll = "\033[0m"
Bold = "\033[1m"
Dim = "\033[2m"
Underlined = "\033[4m"
Blink = "\033[5m"
Reverse = "\033[7m"
Hidden = "\033[8m"
ResetBold = "\033[21m"
ResetDim = "\033[22m"
ResetUnderlined = "\033[24m"
ResetBlink = "\033[25m"
ResetReverse = "\033[27m"
ResetHidden = "\033[28m"
Default = "\033[39m"
Black = "\033[30m"
Red = "\033[31m"
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
Magenta = "\033[35m"
Cyan = "\033[36m"
LightGray = "\033[37m"
DarkGray = "\033[90m"
LightRed = "\033[91m"
LightGreen = "\033[92m"
LightYellow = "\033[93m"
LightBlue = "\033[94m"
LightMagenta = "\033[95m"
LightCyan = "\033[96m"
White = "\033[97m"
BackgroundDefault = "\033[49m"
BackgroundBlack = "\033[40m"
BackgroundRed = "\033[41m"
BackgroundGreen = "\033[42m"
BackgroundYellow = "\033[43m"
BackgroundBlue = "\033[44m"
BackgroundMagenta = "\033[45m"
BackgroundCyan = "\033[46m"
BackgroundLightGray = "\033[47m"
BackgroundDarkGray = "\033[100m"
BackgroundLightRed = "\033[101m"
BackgroundLightGreen = "\033[102m"
BackgroundLightYellow = "\033[103m"
BackgroundLightBlue = "\033[104m"
BackgroundLightMagenta = "\033[105m"
BackgroundLightCyan = "\033[106m"
BackgroundWhite = "\033[107m"
Your Program
print(f"[{bcolors.Green}1{bcolors.ResetAll}] Create new password")
print('[2] See existing passwords')
print('[3] Exit')
Output:

Stuck on AttributeError: 'int' object has no attribute 'reindex' when trying to save workbook in openpyxl

I can't figure this one out. It's complaining about the wb.save() line. I have no idea what's causing it after banging my head on this. I suspect it has something to do with trying to open a blank sheet and saving it after doing stuff with formatting, but I can't imagine what I'm doing there that's causing this problem. It worked fine when I opened an existing spreadsheet and did manipulations, but that required me to have an existing spreadsheet in the first place. Here, I'm trying to start a new spreadsheet from scratch.
from bs4 import BeautifulSoup
from lxml import etree
import os, codecs
import imageFilesSub
import re
import openpyxl, lxml
from openpyxl.utils import get_column_letter, column_index_from_string
homeEnv = 0 # 1 - home, 0 - work
if homeEnv:
filesDir = r'K:\Users\Johnny\My Documents\_World_of_Waterfalls\Website\tier 2 pages\tier 3 pages\tier 4 pages'
filesOutDir = r'K:\Users\Johnny\My Documents\_World_of_Waterfalls\WordPressSite'
else:
filesDir = r'..\old_travelblog_writeups'
filesOutDir = r'./'
# First get the list of files to parse
filesInDir = os.listdir(filesDir)
filesToParse = []
for file in filesInDir:
if ('travel-blog' in file) and (file.endswith('-template.html')):
filesToParse.append(file)
# Open up the travelBlog spreadsheet and set it up
wb = openpyxl.Workbook()
sheet = wb.active
sheet.name = "travelBlog List"
sheet['A1'].value = 'Blog No.'
sheet['B1'].value = 'Title'
sheet['C1'].value = 'Category'
sheet['D1'].value = 'Keyword Tags'
sheet['E1'].value = 'Excerpt'
sheet['F1'].value = 'Featured Image Filename'
sheet['G1'].value = 'Featured Image Alt Text'
sheet['H1'].value = 'Start Date'
sheet['I1'].value = 'End Date'
sheet['J1'].value = 'Old Web Address'
sheet['K1'].value = 'New Travel Blog Body Filename'
sheet['L1'].value = 'Old Travel Blog Template to parse'
sheet.freeze_panes = 'C2'
sheet.column_dimensions['A'].width = 10
sheet.column_dimensions['H','I'] = 20
sheet.column_dimensions['B','F','J','K','L'] = 40
sheet.column_dimensions['D','E'] = 50
from openpyxl.styles import Font
headerFontObj = Font(name='Arial', bold=True)
for col in range(1,sheet.max_column):
sheet.cell(row=1, column=col).font = headerFontObj
wb.save('travelBlogParsed.xlsx')
Thanks in advance,
Johnny
I figured it out. The issue was the following lines:
sheet.column_dimensions['H','I'] = 20
sheet.column_dimensions['B','F','J','K','L'] = 40
sheet.column_dimensions['D','E'] = 50
First of all, apparently, you can't use the column_dimensions method on a vector. The argument must be a string. Second, these lines were missing the .width attribute. So those lines should have been:
sheet.column_dimensions['H'].width = 20
sheet.column_dimensions['I'].width = 20
sheet.column_dimensions['B'].width = 40
...
sheet.column_dimensions['E'].width = 50

Unclear on how to import and display an .OBJ file with Python (in Maya)

I've been working on a project for a week now trying different ways to solve this. I'm extremely new to python and programming in general and don't know the basics.
The task is to make a window with a button that imports an external .obj file into the scene and rename it. At one point I was able to do that by putting the files in the "HOME" directory aka My Documents but I lost that piece of code.
I've tried tons of ways but I don't understand the correct syntax at all. I've asked classmates for help as well and we couldn't figure out where to store the obj and how to reference it properly.
I see this thread which seems useful but always returns "No files found" Importing OBJ file to maya scene (MEL/Python).
import maya.cmds as mc
import os
ram = mc.window("RenamerWin", t = "Renamer v 1.0", w = 300, h = 300)
if mc.window(ram, exists = True):
mc.deleteUI("RenamerWin")
#icon
logopath = mc.internalVar(upd = True) + "icons/icon.jpg"
mc.columnLayout(adj = True)
mc.image (w = 300, h = 100, image = logopath)
mc.separator (h = 25, style = 'double')
mc.text("Welcome to your Custom Forest Builder!")
rockW = mc.intSliderGrp(l = "width", min = 0, max = 10, field = True)
rockH = mc.intSliderGrp(l = "height", min = 0, max = 10, field = True)
rockD = mc.intSliderGrp(l = "depth", min = 0, max = 10, field = True)
mc.button(l = "Create a Rock", c = "myRock()")
#Name the Rock
rockName = mc.textFieldGrp (l="renamer", editable = True)
mc.button (l = "Name the Rock", c = "myRockRenamer()")
mc.showWindow(ram)
def myRockRenamer():
finalName = mc.textFieldGrp(rockName,q = True, text = True)
mc.rename(finalName)
mc.showWindow(ram)
def myRock():
myRockWidth = mc.intSliderGrp(rockW, q = True, value = True)
myRockHeight = mc.intSliderGrp(rockH, q = True, value = True)
myRockDepth = mc.intSliderGrp(rockD, q = True, value = True)
finalRock = mc.file(os.path.join(os.getenv('E:\2015\2. Tech Art Programming\Forest Builder'), 'rock.obj'), open = True, force = True)
finalRock.scale( myRockWidth, myRockHeight, myRockDepth)
Questions:
Do I store the .obj in the same folder as the .mb file? I want to be able to zip this code.
Do I have to load the file into maya first then use another piece of code to display it?
Can you link me to some references? I've searched google over and over again. maybe I've stumbled across the answer but didn't understand what I was looking at.
How to I store this other than in the maya folder on my PC?
logopath = mc.internalVar(upd = True) + "icons/icon.jpg"
When I get the window to open and try to press the button I don't get an error about the file not being found anymore (I did before).
"# Error: TypeError: file C:\Program Files\Autodesk\Maya2015\bin\python27.zip\ntpath.py line 96: object of type 'NoneType' has no len()"
Thank you SO much for any help.
I'm not sure if your problem is that you can't auto-find the path to your obj, or you can't get it to import/rename afterwards?
I've just made a quick example of how I would do it:
import maya.cmds as cmds
new_name = "Renamed_OBJ"
my_file_path = "C:/Temp/OBJ_Temp.obj"
import_nodes = cmds.file(my_file_path,i=True,type="OBJ",rpr="OBJ_Import",rnn=True)
transform_nodes = cmds.ls(import_nodes,type="transform")
for t_node in transform_nodes:
print(t_node)
cmds.rename(t_node,new_name)
A few things; You can use i=True + type="OBJ" in the file command to import objs and add rnn=True to get it to return all the nodes it just imported.
Then you can sort through them a pick out the transform nodes, and rename and scales those.
This documentation helps me a lot in times like this: https://help.autodesk.com/view/MAYAUL/2020/ENU/?guid=__CommandsPython_index_html
I hope it helps.
You aren't escaping the backslashes in your file path, so maya sees them as special chararacters. Try
finalRock = mc.file(os.path.join(os.getenv('E:\\2015\\2. Tech Art Programming\\Forest Builder'), 'rock.obj'), open = True, force = True)
or
finalRock = mc.file(os.path.join(os.getenv('E:/2015/2. Tech Art Programming/Forest Builder'), 'rock.obj'), open = True, force = True)

Categories

Resources