openpyxl format worksheet for printing? - openpyxl

Using python3 with openpyxl. Is it possible to format a worksheet for (paper) printing? i.e. I would need to change the excel defaults to print two-sided, landscape orientation, print the entire workbook, etc. etc. etc. so I could just open the excel file and hit print.
Simple yes or no answer is fine, I saw there are some methods under the worksheet class called e.g. 'A3' or 'Executive' which in theory should correspond to paper sizes but they seem to be string values of integers?

Yes, this possible.
This is a quite valid question and precise enough to be answered.
In the docs, there is this section:
https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/worksheet/page.html#PrintPageSetup
Programmatically define the data:
You can customize your XLSX by extending their class PrintPageSetup, passing your values like:
wb = openpyxl.Workbook()
ws = wb.get_active_sheet()
ws.title = "Your Tab Title"
# Printer Settings
ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
ws.page_setup.paperSize = ws.PAPERSIZE_A3
# Property settings
wsprops = ws.sheet_properties
wsprops.tabColor = "1072BA"
wsprops.filterMode = False
wsprops.pageSetUpPr = PageSetupProperties(fitToPage=True, autoPageBreaks=False)
wsprops.outlinePr.summaryBelow = False
wsprops.outlinePr.applyStyles = True
Fill data into a prepared template:
Also, if you prefer, you can prepare your document in Excel, save it as a template and then open it via openpyxl and dynamically add your actual data.
This is outlined in the docs as well:
https://openpyxl.readthedocs.io/en/stable/tutorial.html#loading-from-a-file
from openpyxl import load_workbook
wb2 = load_workbook('test.xlsx')
print wb2.get_sheet_names()
['Sheet2', 'New Title', 'Sheet1']

This question really is too broad. In Excel there are many settings related to printing but you should probably look at the documentation: https://openpyxl.readthedocs.io/en/latest/print_settings.html

Related

When creating a Google Sheet with C#, how do I select a folder location?

I have the following code that creates a Google Sheet in my root drive folder:
static void CreateSheet()
{
// Create a new sheet with a single tab
string sheetName = "Test Create Sheet";
var NewSheet = new Google.Apis.Sheets.v4.Data.Spreadsheet();
NewSheet.Properties = new SpreadsheetProperties();
NewSheet.Properties.Title = sheetName;
var newSheet = service.Spreadsheets.Create(NewSheet).Execute();
SpreadsheetId = newSheet.SpreadsheetId;
Sheet = "Sheet1";
}
I cannot seem to find syntax to update the location by folderid.
Is this even an option?
Is this even an option? [Answer:] No
According to the official Google documentation for creating a spreadsheet using the Sheets API:
"There’s no option to create a spreadsheet directly within a specified Drive folder using the Sheets API. By default, the created spreadsheet is saved to the user’s root folder on Drive."
However, there are alternative options to saving a file to a Drive folder provided in the official documentation that will point you in the right direction.

How to program a PowerPoint custom object like Thinkcell objects?

I am very new to PowerPoint add-on development so please bear with me.
There are many objects that can be inserted into a PowerPoint slide, such as text box, shape, chart, etc. Is there a way to build my own custom object with custom properties and functionalities? For example, with the Thinkcell add-on, you can insert a Thinkcell chart object, connect it to Excel workbook, edit it, and show it. To the best of my understanding, this is a kind of custom object built into the Thinkcell add-on.
How can I build a custom object like this?
I have checked some tutorials on building a PowerPoint add-on with VBA, VSTO, and Javascript. To the best of my understanding, these technologies allow users to build some user interfaces to interact and modify the PowerPoint slides, such as creating and modifying elements in the slides. However, I don't see examples of creating a custom object using these technologies. Thus I am very curious about how add-ons create their custom element.
Thanks!
First, you will need to install the necessary npm packages and set up the development environment.
For example, you can use the following command to install the Office.js library:
npm install #microsoft/office-js
Then, you can use the following code to create a custom object in a PowerPoint add-in:
Office.initialize = function () {
// Create a new shape on the active slide
var shape = PowerPoint.createShape("MyCustomObject", Office.MsoAutoShapeType.msoShapeRectangle, 50, 50, 100, 100);
// Add a custom property to the shape
shape.customProperties.add("dataSource", "Excel workbook");
// Define a function to be called when the user clicks on the shape
shape.click = function () {
// Open the Excel workbook and display the data
Office.context.ui.displayDialogAsync("https://example.com/excel-workbook", {height: 50, width: 50});
};
};
Here is how you might accomplish this using VBA:
Sub ChangeObjectColor()
Dim obj As Shape
' Get a reference to the custom object
Set obj = ActivePresentation.Slides(1).Shapes("MyObject")
' Check the value of the FillColor property
If obj.FillColor = "red" Then
' Set the fill color of the object to red
obj.Fill.ForeColor.RGB = RGB(255, 0, 0)
ElseIf obj.FillColor = "green" Then
' Set the fill color of the object to green
obj.Fill.ForeColor.RGB = RGB(0, 255, 0)
End If
End Sub

Attaching file to PDF via Access VBA using Adobe SDK

I'm trying to automatically add an attachment to a PDF file through VBA.
From what I can tell it is possible to handle this through FileAttachment annotations.
Dim testAnno As Object
Dim props As Object
Set testAnno = jso.AddAnnot
Set props = testAnno.getProps
props.Type = "FileAttachment"
' Code to attach file to PDF as attachment ......
testAnno.setProps props
I've found the following example in the Adobe documentation so essentially looking for a VBA equivalent to this:
var annot = this.addAnnot({
page: 0
type: "FileAttachment",
point: [400,500],
author: "A. C. Robat",
contents: "Call Smith to get help on this paragraph.",
cAttachmentPath: "/d/a.pdf" ,
});

apply text formatting from string to text for FlowDocument in richtextbox

I know that when adding text/content/DataContext in XAML you refer to resource dictionary or inline mark up for styling around text or in template.
Q:
However I'm having trouble trying to find a way to do the following:
Data is coming from a View Model/Model that is pulled from a database.
(string value)
I am a <Bold>smart</Bold> man.
to show in a flow document like this:
I am a smart man.
Q end
Either by binding to a converter, behavior, or would saving the paragraph/document that I put in the flow document to a .rtf file in memory stream be a better option?
I've tried to utilize the option for behavior listed > here < but that is for text block and unable to redirect for type text instead of text block.
Trying to make it streamlined.
Tried to use data binding and apply the converter but even though I have the resource for the behavior / converter, it work due to the type conversion.
One clever solution is presented by Rockford Lhotka in post Set rich text into RichTextBlock control. His idea is to create a custom control which then creates the RichTextBlock using XamlReader.Load.
This allows you to use code like the following:
<local:RichTextDisplay Xaml="{Binding Hello}" HorizontalAlignment="Center"
VerticalAlignment="Center"/>
Where Hello is:
public string Hello { get; set; } = "I am a <Bold>smart</Bold> man.";
With a result:
If you use UWP/Win 8.1 XAML, you can use the original code from the blog post with the following small change (Paragraphs added):
<UserControl
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"">
<Grid>
<RichTextBlock><Paragraph>");
xaml.Append(ctl.Xaml);
xaml.Append(#"
</Paragraph></RichTextBlock>
</Grid>
</UserControl>
");
To answer my own question:
My case was creating a Document style display for user to update and save as a PDF, but I didn't want to rely on Office being on our application Server.
So I resolved this in my case by using a full "doc.RTF" document and importing that as a memory stream/string and apply my needed updates for values to that.
i.e. VB.net snippet example
Using uStream = Assembly.GetExecutingAssembly.GetManifestResourceStream("Resourcefilepath.rtf")
Using mStream As system.IO.MemoeryStream = New MemoryStream()
uStream.CopyTo(mStream)
rtfstring = Encoding.UTF8.GetSTring(mStream.toArray())
'--Do the updates to the needed string as needed:
rtfstring.Replace("Value","UpdatedValue")
'--Load Property Memory String this method is returnind
RTFDataProperty = New MemoryStream(Encoding.UTF8.GetBytes(rtfstring))
End Using
End Using
Then I loaded my XAML Rich Text Box with that memory stream as DataFormats.Rtf.
RichTextBox1.SelectAll()
RichTextBox1.Selection.Load(ClassName.RTFDataProperty, DataFormats.Rtf)
This gave me a template for formatting and layout of that document. (More of a case scenario and not a normal practice)
I also wanted to apply a starting selection so here is what I did there:
'--Get my RichTextBox Text
rtbtext As String = New TextRange(RichTextBox1.Document.contentStart, RichTextbox1.Document.ContentEnd).Text
Dim strStartSelection As String = "Comments..."
Dim startTP As TextPointer
Dim endTP As TextPointer
'--Loop through the paragraphs of the richtextbox for my needed selection starting point:
For Each para As Paragraph In RichTextBox1.Document.Blocks
Dim paraText As String = New TextRange(para.ContentStart, para.ContentEnd).Text
If paraText = "" Then
Dim pos As TextPointer = para.ContentStart
startTP = pos
endTP = startTP.GetPositionAtOffset("".Length + 3) '--my string had ... on the end so had to add for avoiding the escape of that on length
RichTextBox1.Selection.Select(startTP, endTP)
RichTextBox1.Focus()
Exit For
End If
Next
This is the simple VB.net code layout, but you can simplify and adjust from there if you find it useful.
Thanks

Setting value to flashvars property doesn't work

I'm trying to set value to the property FlashVars when inserting shockwave flash movie to PowerPoint 2010 using vba like this:
Dim s As Shape
Set s = ActivePresentation.Slides(1).Shapes.AddOLEObject(0, 0, -1, -1, ClassName:="ShockwaveFlash.ShockwaveFlash")
With s.OLEFormat.Object
.FlashVars = "parm1 = val1"
.EmbedMovie = True
.Movie = "D:\Samples\test.swf"
End With
However, after executing the setting command (s.OLEFormat.Object.FlashVars = "parm1 = val1" ), the value of FlashVars remains empty. Do you have any idea about this weird behavior ?
Thanks,
I have no idea about embedding Flash in this fashion, but in the browser an alternative to defining a FlashVars object can be to append the variables to the SWF file name. That might be worth a try if a proper solution does not present itself.
.Movie = "D:\Samples\test.swf?parm1=var1"