Page orientation doesn't work in OpenOffice with Python - python

I am trying to set the pageorientation in an OpenOffice document with python. The following code i use to try this:
import json
from win32com.client import Dispatch as Dispatch
svm = Dispatch("com.sun.star.ServiceManager")
svm._FlagAsMethod("Bridge_GetStruct")
coreflect = svm.createInstance("com.sun.star.reflection.CoreReflection")
desktop = svm.createInstance("com.sun.star.frame.Desktop")
doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank",0, [])
txt = doc.getText()
cur = txt.createTextCursor()
Then i tried two different approaches:
p = doc.getPagePrintSettings()
p[8].Value = True
doc.setPagePrintSettings(p)
and
oStyleFamilies = doc.getStyleFamilies()
oObj1 = oStyleFamilies.getByName("PageStyles")
oObj2 = oObj1.getByName("Default")
oObj2.IsLandscape = True
Both give no error, but the page is still in Portrait.. Anybody has an idea?
Thanks in advance!!

try : oObj2.setPropertyValue("IsLandscape",True)
see http://codesnippets.services.openoffice.org/Calc/Calc.SwitchOrientation.snip

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?

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

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.

Python / Django compare and update model objects

Iv only just started python but have learned a lot over the last few month, now I have hit a wall about updating objects on a model at a good speed.
I have a model called Products and this is populated from a csv file, every day this file get updated with changes like cost, and quantity, I can compare each line of the file with the Products Model but having 120k lines this takes 3-4hours.
What process can I take to make this process this file faster. I only want to modify the objects if cost and quantity have changed
Any suggestions how I tackle this?
Ver3 of what i have tried.
from django.core.management import BaseCommand
from multiprocessing import Pool
from django.contrib.auth.models import User
from pprint import pprint
from CentralControl.models import Product, Supplier
from CentralControl.management.helpers.map_ingram import *
from CentralControl.management.helpers.helper_generic import *
from tqdm import tqdm
from CentralControl.management.helpers.config import get_ingram
import os, sys, csv, zipfile, CentralControl
# Run Script as 'SYSTEM'
user = User.objects.get(id=1)
# Get Connection config.
SUPPLIER_CODE, FILE_LOCATION, FILE_NAME = get_ingram()
class Command(BaseCommand):
def handle(self, *args, **options):
list_in = get_file()
list_current = get_current_list()
pool = Pool(6)
pool.map(compare_lists(list_in, list_current))
pool.close()
def compare_lists(list_in, list_current):
for row_current in tqdm(list_current):
for row_in in list_in:
if row_in['order_code'] == row_current['order_code']:
#do more stuff here.
pass
def get_current_list():
try:
supplier = Supplier.objects.get(code='440040')
current_list = Product.objects.filter(supplier=supplier).values()
return current_list
except:
print('Error no products with supplier')
exit()
def get_file():
with zipfile.ZipFile(FILE_LOCATION + 'incoming/' + FILE_NAME, 'r') as zip:
with zip.open('228688 .csv') as csvfile:
reader = csv.DictReader(csvfile)
list_in = (list(reader))
for row in tqdm(list_in):
row['order_code'] = row.pop('Ingram Part Number')
row['order_code'] = (row['order_code']).lstrip("0")
row['name'] = row.pop('Ingram Part Description')
row['description'] = row.pop('Material Long Description')
row['mpn'] = row.pop('Vendor Part Number')
row['gtin'] = row.pop('EANUPC Code')
row['nett_cost'] = row.pop('Customer Price')
row['retail_price'] = row.pop('Retail Price')
row['qty_at_supplier'] = row.pop('Available Quantity')
row['backorder_date'] = row.pop('Backlog ETA')
row['backorder_date'] = (row['backorder_date'])
row['backorder_qty'] = row.pop('Backlog Information')
zip.close()
#commented out for dev precess.
#os.rename(FILE_LOCATION + 'incoming/' + FILE_NAME, FILE_LOCATION + 'processed/' + FILE_NAME)
return list_in
I have once faced a problem of slow load of data, I can tell you what i did maybe it can help you somehow, I passed the execution to debug mode and tried to find out wich colomn is causing the slow loading, and everytime i see that a colomn is causing the problem I add an index on it (in the SGBD --> postgreSQL in my case), and it worked. I hope that you are facing the same problem so my answer can help you.
Here it's rough idea:
1, when reading csv, use pandas as suggest by #BearBrow into array_csv
2, convert the obj data from Django into Numpy Arrary array_obj
3, don't compare them one by one , using numpy substraction
compare_index = (array_csv[['cost',['quantity']]] - array[['cost',['quantity']]] == 0)
4, find the updated column
obj_need_updated = array_obj[np.logic_any(compare_index['cost'], compare['quantity'])]
then use Django bulk update https://github.com/aykut/django-bulk-update to bulk update
Hope this will give you hints to speed up your code

How to add a link to a Visio document via Python

I googled for some code to create Visio documents via Python. I want to add shapes, and have hyperlinks. So that you can click on the shape, or preferably on the text inside the shape, and get to a URL.
import os
import win32com.client
from win32com.client import constants
appVisio = win32com.client.Dispatch("Visio.Application")
appVisio.Visible =1
doc = appVisio.Documents.Add("Basic Diagram.vst")
pagObj = doc.Pages.Item(1)
stnObj = appVisio.Documents("Basic Shapes.vss")
mastObj = stnObj.Masters("Rectangle")
shpObj1 = pagObj.Drop(mastObj, 4.25, 5.5)
shpObj1.Text = "This is some text."
shpObj2 = pagObj.Drop(mastObj, 2, 2)
shpObj2.Text = """This is some more text. {\field{\*\fldinst HYPERLINK "http://www.google.com/"}{\fldrslt http://www.google.com}}"""
connectorMaster = appVisio.Application.ConnectorToolDataObject
connector = pagObj.Drop(connectorMaster, 0, 0)
connector.Cells("BeginX").GlueTo(shpObj1.Cells("PinX"))
connector.Cells("EndX").GlueTo(shpObj2.Cells("PinX"))
doc.SaveAs(r'C:\utils\MyDrawing.vsd')
doc.Close()
appVisio.Visible =0
appVisio.Quit()
The RTF link is ignored - I tried that. Visio can add hyperlinks in the UI. So... does anyone know how I can add a link via Python here?
Visio only supports links on a shape (rather than within the text itself). A shape has Hyperlinks collection of Hyperlink objects and so you can add as follows:
# shpObj2.Text = """This is some more text. {\field{\*\fldinst HYPERLINK "http://www.google.com/"}{\fldrslt http://www.google.com}}"""
shpObj2.Text = "This is a shape with multiple links."
shp2Hyperlink1 = shpObj2.Hyperlinks.Add()
shp2Hyperlink1.Name = "Google"
shp2Hyperlink1.Address = "http://www.google.com"
shp2Hyperlink2 = shpObj2.Hyperlinks.Add()
shp2Hyperlink2.Name = "BBC"
shp2Hyperlink2.Address = "http://www.bbc.co.uk"
Under the covers this is just writing cells into the ShapeSheet:

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