Set workbook view with openpyxl? - python-3.x

Is it possible to set the Workkbook View to "Page Layout" with openpyxl? Looking on stackoverflow and the openpyxl docs I can't seem to find it. Is it possible?

Yes, it is possible with this code:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
#Value must be one of {'pageBreakPreview', 'pageLayout', 'normal'}
ws.sheet_view.view = "pageLayout"
How did I find out?
To my surprise I also could not find any tutorials or anything in the docs on this topic.
I did a little digging and if you type into the terminal:
print(ws.sheetview)
A series of parameters will pop out, including the one we are looking for (the view attribute):
Parameters:
windowProtection=None, showFormulas=None, showGridLines=None, showRowColHeaders=None, showZeros=None, rightToLeft=None, tabSelected=None, showRuler=None, showOutlineSymbols=None, defaultGridColor=None, showWhiteSpace=None, veSymbols=None, defaultGridColor=None, showWhiteSpace=None, view=None, topLeftCell=None, colorId=None, zoomScale=None, zoomScaleNormal=None, zoomScaleSheetLayoutViewalePageLayoutNone,ne, selection=[<openpyxl.worksheet.views.S=None, zoomScalePageLayoutView=None, zoomToFit=None, workbookViewId=0, pane=None, selection=[<openpyxl.worksheet.views.Selection object>
You can then set this attribute according to the code on the top of the answer to the three predetermined values otherwise you will get an ValueError: Value must be one of {'pageBreakPreview', 'pageLayout', 'normal'}.

Related

Openpyxl - Setting Active Sheet (page.append not working as expected)

I've tried implementing multiple solutions from existing posts, like this one, to no avail:
openpyxl Set Active Sheet
I have a workbook with n number of sheets that I want to iteratively step through, and apply header information to. As far as I can tell, using wb.active = i is setting the active worksheet, but when I follow up with page.append(header), I end up with the header appended n times, ONLY to the index 0 sheet. This is essentially the same q as the link above, but the solution doesn't seem to work.
What am I missing here? I wonder if I need to specify an index for page.append(), but that doesn't seem to be a valid argument for that func.
CODE
header = ['Time [sec]', 'Altitude [km]', 'Velocity [km/s]']
for i in range(len(wb.sheetnames)):
wb.active = i
print(wb.active)
page.append(header)
wb.save(path)
CONSOLE (verifies that the wb.active function is working, but the sheets specified aren't being appended)
<Worksheet "ORB1">
<Worksheet "ORB2">
<Worksheet "ORB3">
<Worksheet "ORB4">
<Worksheet "ORB5">
Here is another version which produces the same result (5x headers applied only to the first sheet).
header = ['Time [sec]', 'Altitude [km]', 'Velocity [km/s]']
for i, s in enumerate(wb.sheetnames):
page.append(header)
wb.save(path)
This one is SOLVED but I want to keep the q up because the solution is... weird.
Earlier in the code I was assigning page = wb.active, and then later using page.append(header).
The issue with that ^, has to do with the format for setting the active sheet.
wb.active is used such that wb.active = sheet_index, rather than the typical function structure where wb.active(sheet_index).
Because of this bizarre arg format, simplifying "wb.active" to "page" breaks this function.
TLDR: This does not work...
page = wb.active
page.append(header)
You must use...
wb.active.append(header)
No idea why that function has such a strange structure, but I suspect I'm not the only person to have had this issue.

Get Excel Sheet Direction with Xlrd

How can check the excel sheet direction with python?. my mean is Left_to_Right or Right_to_Left.
You need to load the workbook using formatting_info parameter like below.
wb = xlrd.open_workbook("table.xls", formatting_info=True)
You can then use wb.xf_list attribute to retrieve formatting information like text_direction. Each cell in the workbook will have have an xf_index attribute allowing you to retrieve corresponding information in the wb.xf_list.
According to the documentation, these are the possible values for the text_direction attribute.
0 = according to context; 1 = left-to-right; 2 = right-to-left

commentsthreaded.count property not available in excel 365 vba

I am trying to adjust some workbook audit code for the new threaded comments. Basically the code would cycle through all workbook comments (notes) and consolidate them into a new sheet at the end of the workbook.
With what is now notes, I use the following (noting cmt1 is declared as a comment object and wsSource is a worksheet object)
For Each cmt1 In wsSource.Comments
'Collect comment data for testing/pasting
strSheetname = wsSource.Name
strCmt = cmt1.Text
strCellref = cmt1.Parent.Address
strContent = cmt1.Parent.Formula
etc.
Now with threaded comments, the same type of approach didn't work. I am trying to do a numerical loop using a counter and having code like the below:
For x = 1 to wsSource.commentsthreaded.count
However the count property doesn't work. According to the nmicrosoft website, it should be one of the 4 available properties.
https://learn.microsoft.com/en-us/office/vba/api/excel.commentsthreaded
Does anyone else have this issue? Any way to fix it?
Issue resolved - it looks like the problem was the Excel version. I was running 1904 and it now works since updating to 1906.

excel vba listobject HeaderRowsRange

I am working with list objects in excel and there is one thing that puzzles me:
according to this and many other sites I visited the following line of code is a range:
mytable.headerRowRange("nameofColumn")
mytable being a listobject of a particular sheet.
what I wand to do is hide that column
but this would not work:
mytable.headerRowRange("nameofColumn").EntireColumn.Hidden=True
Why?
the error is: Invalid procedure call or argument.
thanks.
mytable.ListColumns("ID").Range.EntireColumn.Hidden = True
You could also have done
mytable.HeaderRowRange.Find("id").EntireColumn.Hidden = True

Is is possible to insert an image into an excel cell via COM?

I have used automation to insert values into a cell, however I have never seen any documentation, for example, that demonstrate inserting anything other than text and/or formula's.
Has anybody been able to insert an image from an external application?
Dim FileName as string
FileName="c:\text.jpg"
Set NewPic = ActiveSheet.Pictures.Insert(FileName)
NewPic.top=100
NewPic.left=100
If you want to position the picture to a specific cell then select that cell as a range and use that ranges top/left/with to position the picture.
Samples: http://exceltip.com/st/Insert_pictures_using_VBA_in_Microsoft_Excel/486.html
Note: In Excel cells cannot contain pictures. The pictures live on an invisible drawing layer that floats about the cells. They can be positioned based on the cell coordinates, which makes it feel like they are living "in" the cells.
I see it's already been answered, but see my post here.
Basically rather than use the Worksheet.Pictures.Insert method (which the MSDN recommends you don't use directly, and which returns a raw COM object), try the Worksheet.Shapes.AddPicture method instead.
Dim range As Microsoft.Office.Interop.Excel.Range
Dim pic as Microsoft.Office.Interop.Excel.Shape
Dim filePath as String
range = ...
filePath = ...
pic = range.Worksheet.Shapes.AddPicture(filePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, range.Left, range.Top, 300, 300)
It's not quite as straightforward because you have to specify the exact position and dimensions, but otherwise, pretty cool!
Sure, the following code gives a good example using the Microsoft Interop libraries:
string excelfilename = #"C:\excelfile.xlsx";
string picturename = #"C:\image.jpg";
object missing = Type.Missing;
Microsoft.Office.Interop.Excel.Application app = new ApplicationClass();
Workbook book = app.Workbooks.Add(missing);
Worksheet sheet = (Worksheet)book.ActiveSheet;
Pictures pics = (Pictures)sheet.Pictures(missing);
pics.Insert(picturename, missing);
book.SaveAs(excelfilename, missing, missing, missing, missing, missing, XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
app.Quit();
app = null;

Resources