Can I find and apply PatternFill to all blank (empty cells) in a worksheet with openpxl - formatting

Newbie! Please be gentle.
I'm trying to save a worksheet using openpyxl with some formatting.
I have blank/empty cells in my worksheet and I would like to format/fill them.
So. Find all blank/empty cells
Apply PatternFill
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
from openpyxl.styles import Fill, Color
catalogwb = openpyxl.load_workbook(currentDir + fileName)
catalogws = catalogwb.active
catalogws1 = catalogwb.create_sheet("Sheet2")
testcell = catalogws['B2']
testcell.fill = PatternFill("solid", fgColor="DDDDDD") #works!
max_row=catalogws.max_row
max_col=catalogws.max_column
print(max_row , max_col)
catalogws.column_dimensions['B'].width = 80
myFill = PatternFill("solid", fgColor="DDDDDD")
catalogws.cell(row=max_row,column=max_col).fill = myFill #works!
Spent too much time on this.
Thanks!

Related

I am trying to switch every empty cell to one filled with the number 1

Hi I am currently using openpyxl and am trying to swap every empty cell to one with the number 1, and then eventually one filled in with red. Here is my code so far:
import openpyxl
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.utils import column_index_from_string
#redFill = PatternFill(fill_type=None, start_color='F2DCDB', end_color='F2DCDB')
wb = openpyxl.load_workbook('MRR.xlsx')
sheet = wb["Monthly MRR "]
for r in range(7, 793):
for col in range(4,21):
current_cell = sheet.cell(row=r, column=col).value
if current_cell == None:
current_cell = "LL"
wb.save("updatedMRR.xlsx")
Even though I loop through every item, it does not seem to change any of the cells.
You should change your code so that you refer to the actual cell and explicitly check and set its value. Your code currently checks a copy of the value and then overwrites the copy but not the actual cell.
current_cell = sheet.cell(row=r, column=col)
if current_cell.value is None:
current_cell.value = "LL"
PS use ws.iter_rows() rather than your own counter.

Excel - Fill a cell with different colors

I need to fill a cell with different colors as in this picture (3 rows are merged vertically and colors are drawn manually in this picture using 3 rectangular shapes):
The only way I could find to fill part of a cell is using conditional formatting (by setting style as data bar and fill as solid) but it support only one color.
Is this possible with or without VBA?
It is possible.
I have found two ways to do that.
1- Using a black square shaped character (character code 2588 – vba: ActiveSheet.Cells(1, 1) = ChrW(&H2588)) and color them according to percentage. This character fills the cell height and also there is no spacing between them which allows filling a cell completely (Sure you should consider left indent in a cell). Only issue here that you cannot use a lot of characters in one cell; I use 30 of them and scale the number of characters according to 30 (ie. 50% red means 15 red character-2588).
2- It is same as what #Doktor Oswaldo has suggested: Inserting a plot in a cell using cell's position and size in pixels. This method has one big advantage: you can show the ratios exactly. In addition, you can fill a data series with a pattern as well. However if you have a lot of plots, you will sacrifice from Excel performance. For plot settings, I use following VBA code:
'Define var's
Dim src As Range, targetCell As Range
Dim chacha As ChartObject
'Set var's
Set src = Worksheets("Sheet1").Range("B1:B3")
Set targetCell = Worksheets("Sheet1").Range("C2")
'Create plot at the target cell
Set chacha = Sheets("Sheet1").ChartObjects.Add(targetCell.Left, targetCell.Top, targetCell.Width, targetCell.Height)
'Change plot settings to fill the cell
With chacha.Chart
.ChartType = xlBarStacked
.SetSourceData Source:=src, PlotBy:=xlRows
.Axes(xlValue).MinimumScale = 0
.Axes(xlValue).MaximumScale = 100
.Axes(xlCategory).Delete
.Axes(xlValue).Delete
.Legend.Delete
.PlotArea.Top = -50
.PlotArea.Left = -50
.PlotArea.Width = targetCell.Width
.PlotArea.Height = targetCell.Height
.ChartGroups(1).GapWidth = 0
End With
chacha.Chart.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
chacha.Chart.SeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(0, 0, 255)
chacha.Chart.SeriesCollection(3).Format.Fill.ForeColor.RGB = RGB(255, 255, 0)
In the code I modified the series colors manually which can also be automatized. Following is the screenshot of both methods. The Cell "C1" is filled with block characters and "C2" is a chart.
Note: You might get an error at the line ".PlotArea.Top". To solve this issue, please check: Error setting PlotArea.Width in Excel, VBA (Excel 2010)

Read values from named ranges with openpyxl

How can I read values from named ranges in Excel with openpyxl?
I've found the sourcecode at http://openpyxl.readthedocs.org/en/latest/_modules/openpyxl/workbook/names/named_range.html but I can't figure out how to use it properly.
wb = openpyxl.load_workbook(excel_file_name)
rng = wb.get_named_range(name_of_range).destinations[0]
sheet = rng[0]
address = rng[1].replace('$','')
val = sheet[address].value

Fill pattern to excel cell using VB.NET

How to fill a pattern to excel cell?
Based on few posts on this forum, I tried to use following, but no success so far.
a)
oWB1.Worksheets(i).Cells(7, 3).Interior.PatternIndex = 5
b)
Dim style As Microsoft.Office.Interop.Excel.Style
style = oWB1.Styles.Add("Style1")
style.Interior.Pattern = Microsoft.Office.Interop.Excel.XlPattern.xlPatternSolid
oWB1.Worksheets(i).Cells(7, 3).Style = "Style1"
Any help will be really appreciated.
Thanks
This (Excel VSTO) code works:
Dim rng As Range = activeSheet.Range(1,1)
rng.Style = "Calculation"
"Calculation" is the name of the style.

apache poi: change the font of existing entire sheet

I has a existing workbook containing multiple sheets. I have a sheet which contains some bold cells in it. I want to change the font of this entire sheet retaining the boldness of some of the cells. Can you please provide me the code snippet?
You will have to create more than one style for the workbook:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle fontStyleBold = wb.createCellStyle();
XSSFCellStyle fontStyleNormal = wb.createCellStyle();
and assign the cells you want.