Do not display 0's in workbook xlsxwriter - xlsxwriter

There is a way to have a workbook not display 0 values under Excel->Preferences (on mac). Is there a way to set this with xlsxwriter? I know I can do this via conditional formatting for each sheet, but it involves setting the font to be an invisible color and my background colors are variable, so that's a lot more complicated.

You can use the worksheet.hide_zero() method, like this:
import xlsxwriter
workbook = xlsxwriter.Workbook('hide_zero.xlsx')
worksheet = workbook.add_worksheet()
worksheet.hide_zero()
worksheet.write('A1', 1)
worksheet.write('A2', 0)
worksheet.write('A3', 1)
workbook.close()
Output:

Related

Openpyxl autosize column size

Morning,
I would like that when cells are added, they adjust to the width of the text, any ideas?
def excel():# Writing on a EXCEL FILE
filename = (f"{myPath}/{day}.{month}.{year}.xlsx")
try:
wb = load_workbook(filename)
ws = wb.worksheets[0] # select first worksheet
except FileNotFoundError:
headers_row = ['Name','Pers. Nummer','Kürse','Funktion','Dienstbeginn','Dienstende','Schitdauer','Bezahlte Zeit','Kommentar']
wb = Workbook()
ws = wb.active
ws.append(headers_row)
wb.save(filename)
ws.append([userfinder,tagesinfo,emptycell,emptycell,emptycell,emptycell,emptycell,emptycell])
for cols in ws.iter_cols( ):
if cols[-1].value:
cols[-1].fill=(PatternFill(fgColor="D5D5D5", fill_type='solid'))
cols[-1].border = Border(left=Side(style='thin'),right=Side(style='thin'),top=Side(style='thin'),bottom=Side(style='thin'))
wb.save(filename)
wb.close()
print(f'{userfinder}-{ivunumber} - {tagesinfo} OK')
excel()
You can use python to resize column width and row height to specific values just by adding lines
ws.column_dimensions['A'].width = 30
ws.row_dimensions[1].height = 20
The above would resize column A to 30 and row 1 height to 20.
There is no auto sizing so you have to figure out the values based on the font sixe and text length of whichever cell is largest (or is to be the determining width).
If your using the headers and these never change then you should be able to determine this easily however if the text may change then you may need to calc text length and determine a formula based on that and font size.
There are discussions and examples in other questions that should help, for starters look at.
Python - Automatically adjust width of an excel file's columns

get cell fill color using openpyxl

I would like to get the background fill value for a particular cell in a sheet using openpyxl. I thought that the selected answer from this post openpyxl : Is there a way to search an Excel spreadsheet for cells with specific fill color? would help me, but it isn't working properly.
Here is my current code:
wb1 = Workbook()
ws1 = wb1.create_sheet('new sheet', 0)
ws1.cell(1,1).value = 0.5 # cell A1
rule = ColorScaleRule(start_type='num', start_value=0, start_color='FFFFFF',
end_type='num', end_value=1, end_color='FF007F')
ws1.add(range_string='A1', cfRule=rule)
print('rgb_fg: ', ws1.cell(1,1).fill.fgColor.rgb)
print('rgb_bg: ', ws1.cell(1,1).fill.bgColor.rgb)
output:
rgb_fg: 00000000
rgb_bg: 00000000
Since I assigned 0.5 as the value of cell "A1" in ws1, then I would have no reason to think that the rgb of this cell would be 00000000 (black). It should be a light salmon red color, which is what I get if the sheet is saved and I view it.
Note I printed fgColor and bgColor just to cover all my bases (or the ones I can think of)
Perhaps something funky happens when a ColorScaleRule is applied to a cell so its fill value can't be read in the way I expect?
Conditional formatting is not handled the same way as static colors. Background colors from those conditional rules are dynamic and therefore left to only be applied by spreadsheet software, not the library itself. Therefore, you will not be able to determine this value with openpyxl.
The good news is that if you were to save the spreadsheet, you would see that your code is correct and the cell does appear pink.

using data validation for copying a named chart form another worksheet

I have been working on a dashboard where I can use drop-down lists to select and copy/paste named charts with the same name from other sheets in the entire workbook.
I'm trying a few things but none works:
Activeworkbook.ChartObjects Range("F2").activate
F2 being the cell with data validation.
I think your select isn't working because you need to use the value in your cell as a string referring to the chartobject in the collection. Change the sheet reference below as needed. I have my cell containing the name of the chartobject and the chartobject itself on the same sheet but it sounds like that's different than your setup.
ThisWorkbook.Sheets("Sheet1").ChartObjects(ThisWorkbook.Sheets("Sheet1").Range("F2")).Activate
Which you could then shorten if you have workbook and worksheet variables referring to ThisWorkbook, your worksheet with your chartobject, and your worksheet with your data-validated name cell.
Thank you for that! It solves the first part of the question, namely using the value in the cell as reference.
The second part is more tricky: I have several sheets with named charts in the workbook and I need the command to copy a particular named chart in the entire workbook.
One option is just to put all my charts into a single worksheet. but ideally I would like to keep them in their respective sheets.
Any way this could work?

change font within a shape ppt

I'm automatically generating a powerpoint slide through VBA, User Forms, and Excel. You run the VBA script in excel, fill out the data, the data goes into cells in excel, then the VBA script pulls the data and puts it into textbox shapes in the slide.
My problem is I want to use different font sizes at different times, so for example 28 pt font for one part and 14 pt for the rest. The problem is that any property changes I make to the textbox applies to all of the text within the shape.
My current workaround is sloppy and is to just generate another textbox over the original and insert spacing in the original so it looks like the larger text is "in" the textbox while it's actually just sitting over a few empty lines set aside.
You can format specific substrings within a string, but it's very cumbersome, for example assuming shp is an object variable representing your textbox:
Sub foo()
Dim shp As Shape
Set shp = ActivePresentation.Slides(1).Shapes("TextBox 3")
shp.TextFrame.TextRange.Text = "Hello, world!"
shp.TextFrame.TextRange.Characters.Font.Size = 14 'applies uniform font to entire shape
shp.TextFrame.TextRange.Characters(1, 5).Characters.Font.Size = 28
End Sub
Example output:
The difficulty of course is working with mixed formats, and I do not think there is any easy solution. It will be up to you to determine what formats you need to "capture", and what subsequently implement the appropriate conditional logic to transfer those formats to the PowerPoint shapes.
One possible alternative -- and this is the route that I would go if I were you -- would be to copy the cell from Excel, and use this method to paste in to PowerPoint. I believe this will create a table consisting of a single cell, in the PowerPoint slide. You will have to make adjustments for size/position, but this should be an order of magnitude easier than trying to capture every possible variation of font formatting:
Sub foo2()
Dim shp As Shape
Dim xl As Object
'Get Excel and copy a specific cell
Set xl = GetObject(, "Excel.Application")
xl.Workbooks("Book35").Sheets("Sheet2").Range("B4").Copy
'Paste that cell in to PowerPoint as a table, preserving formats:
ActivePresentation.Slides(1).Select
Application.CommandBars.ExecuteMso "PasteSourceFormatting"
End Sub
Example output, as copied from the Excel cell:
No need to change the font in excel to reflect in Word. You can do it directly. Just paste the below mentinoed line in Word VBA : -
Activedocument.Shapes("sam").TextFrame.TextRange.Words(1).Font.Size = 28

My Excel VBA conditional formatting (background color) isn't updating

I have an application which opens an Excel workbook and in this workbook there is a sheet which has some cells with conditional formatting (background in red when 1, orange when 2 etc ...).
When there are no values in these cells and I then choose a value from a combobox, it should change the background color but it doesn't. However, when I copy and paste a value from another cell (with conditional formatting), the background color is updated and I have the same problem afterwards (background color doesn't update when I change values).
So I want to create a macro in VBA which allows this update when I change values.
N.B. There are protected cells in the workbook but no protection on these cells.
N.B.2: There are 4 cells with the right background color but they are filled before or during Excel opening (it's not my application).
Application.ScreenUpdating = True 'not working
Application.Calculate 'not working too
another weird thing : if i copy/paste all the values (1,2,3,4) from a cell to another + a ctrl + z, then the conditional formatting works fine for all the cells ...
I've found a solution using Cells.ApplyOulineStyles. It works for the first update of the values. I think i will clear the background for each change and call it again.