Can I control the "Wrap Text" property of a cell using Python+xlwings?
It's currently not implemented but I've opened a feature request here. In the meantime, you can always work around by accessing the underlying COM object on Windows: mysheet.range('A1').api.WrapText = True or appscript object on Mac: mysheet.range('A1').api.wrap_text.set(True).
For anybody like me who comes to this now and doesn't find these solutions are working, I found accessing the pywin32 API directly with work_sheet.range('A:A').api.WrapText = True worked in Python 3.7 and xlwings 0.15.8 in Windows 7 and Excel 2010.
For the newest xlwings version:
import xlwings as xw
wb1 = xw.Book('Book1.xlsm').sheets['Sheet1']
wb1.range('A1').value="It's currently not implemented but I've opened a feature request here. In the meantime, you can always work around by accessing the underlying COM object on Windows: "
wb1.range('A1').WrapText = True
xlwings 0.19.5 this works:
sht.range('A1').api.WrapText = True
Related
I am looking at the answer to the following question: Insert Base64 image to pdf using pyfpdf
The answer suggested here was to override the existing load_resource method.
What I did instead was
class EnhancedPdf(FPDF):
def load_resource(self, reason, filename):
if reason == "image":
if filename.startswith("data"):
f = filename.split("base64,")[1]
f = base64.b64decode(f)
f = BytesIO(f)
return f
else:
return super().load_resource(reason, filename)
However, Pycharm highlights the super call with the message "Unresolved attribute reference "load_resource" for class "FPDF"
In my command line, I ran the commands
from fpdf import FPDF
dir(FPDF)
Inspecting this list, I see load_resource function is indeed not a listed method. Hence my question is why is the load_resource function not visible?
Most probably you are using Python 3.x where x >= 5 .
On the pypi it says that the module has only experimental support for python 3.y where y <= 4 .
Try it with python 2.7 and it might work.
PS: Better try https://pypi.org/project/fpdf2/, the updated version. For bugs or issues see https://github.com/alexanderankin/pyfpdf .
If you really want to use the old version, you can install whatever version you want from the original repo like this
pip install git+https://github.com/reingart/pyfpdf#<branchname of tag or commit>
I've just upgraded to Canopy 1.7.1; I think this problem stems from the change in IPython version from 2.4.1 to 4.1.2.
The issue I have is that calling a DataFrame object in Python seems to use the __print__ method, i.e. there's no difference between typing print df and df into the interpreter, and unfortunately this gives me an all-text output rather than the nice tables I normally get.
So I get something that looks exactly like this when I call df rather than a table:
date flag
1 20151102 0
98663 20151101 1
This happened immediately after the upgrade, and I also tried updating all my packages. I've also looked at this and this, but none of the solutions there work for me. ('display.notebook_repr_html' is already True)
EDIT: The issue seems to do with rendering HTML; typing in
from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))
returns
<IPython.core.display.HTML object>
This has purposely been disabled. I have requested a way to have it re-enabled but but unsupported.
Please see the request. https://github.com/jupyter/qtconsole/issues/165
Note from maintainers: This question is no longer relevant. The bokeh.objects module has not existed for years
I'm trying to run this script:
#Code will be significantly simplified in the 0.4 release
import time
from bokeh.objects import GlyphRenderer
renderer = [r for r in curplot().renderers if isinstance(r, GlyphRenderer)][0]
ds = renderer.data_source
while True:
df = pd.io.json.read_json(url+json_call)
ds.data["x"] = x+N*i
ds.data["y"] = df.rssi
ds._dirty = True
session().store_obj(ds)
time.sleep(1.5)
i+=1
from:
https://www.continuum.io/content/painless-streaming-plots-bokeh
but at this line:
from bokeh.objects import GlyphRenderer
I got:
No module named objects
The version I'm using is
0.11.1
On linux mint 17.1
Note from maintainers: This answer is no longer relevant. The bokeh.objects module has not existed for years
did you try installing bokeh before trying the examples? If not, just run:
pip install bokeh
and try your script again.
if it does not work, it's likely that the bokeh sources changed, so you might want to change the
from bokeh.objects import GlyphRenderer
into
from bokeh.models.renderers import GlyphRenderer
cf the source code
At the first line of your example it states:
#Code will be significantly simplified in the 0.4 release
which means that the example's code was already about to be deprecated at the time of the writing of the tutorial.
So instead of copy/pasting that code, you should try to understand how it works, and recreate it using the documentation and sources:
http://docs.bokeh.org/en/latest/docs/user_guide/quickstart.html#userguide-quickstart
https://github.com/bokeh/bokeh
have fun!
The objects module was deleted in commit 5b5d28304c5ea209e243af5943917fe494d9ef9c (v0.7.1) after being deprecated in 8bb4a2f1f43b39b869c508ef7aee69f7aabb46b8 (v0.7.0). The deprecation message reads: "use bokeh.models instead". I leave finding GlyphRenderer in the current codebase as an exercise for you.
conda update bokeh solved this for me.
Regarding streaming (since that is is the example the OP was interested in), the current and stable streaming API is demonstrated here:
https://github.com/bokeh/bokeh/tree/master/examples/app/ohlc
This simple interface has been the way to efficiently stream to data soruces since 0.11.1, and will continue to be going forward.
The basic idea is to construct a dict with all the columns of a data source, and just the new data that is to be appended:
# construct a source with x and y columns
source = ColumnDataSource(data=dict(x=[....], y=[....]))
# sends the few new data points to the client, does not re-send all the data
source.stream(dict(x=[10, 11], y=[20, 21]))
Typically you'd probably call stream from some kind of periodic callback. The OHLC app linked above is a complete example.
I'm trying to create a python program (using pyUNO ) to make some changes on a OpenOffice calc sheet.
I've launched previously OpenOffice on "accept" mode to be able to connect from an external program. Apparently, should be as easy as:
import uno
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext)
# connect to the running office
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;"
"urp;StarOffice.ComponentContext")
smgr = ctx.ServiceManager
# get the central desktop object
DESKTOP =smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
#The calling it's not exactly this way, just to simplify the code
DESKTOP.loadComponentFromURL('file.ods')
But I get an AttributeError when I try to access loadComponentFromURL. If I make a dir(DESKTOP), I've see only the following attributes/methods:
['ActiveFrame', 'DispatchRecorderSupplier', 'ImplementationId', 'ImplementationName',
'IsPlugged', 'PropertySetInfo', 'SupportedServiceNames', 'SuspendQuickstartVeto',
'Title', 'Types', 'addEventListener', 'addPropertyChangeListener',
'addVetoableChangeListener', 'dispose', 'disposing', 'getImplementationId',
'getImplementationName', 'getPropertySetInfo', 'getPropertyValue',
'getSupportedServiceNames', 'getTypes', 'handle', 'queryInterface',
'removeEventListener', 'removePropertyChangeListener', 'removeVetoableChangeListener',
'setPropertyValue', 'supportsService']
I've read that there are where a bug doing the same, but on OpenOffice 3.0 (I'm using OpenOffice 3.1 over Red Hat5.3). I've tried to use the workaround stated here, but they don't seems to be working.
Any ideas?
It has been a long time since I did anything with PyUNO, but looking at the code that worked last time I ran it back in '06, I did my load document like this:
def urlify(path):
return uno.systemPathToFileUrl(os.path.realpath(path))
desktop.loadComponentFromURL(
urlify(tempfilename), "_blank", 0, ())
Your example is a simplified version, and I'm not sure if you've removed the extra arguments intentionally or not intentionally.
If loadComponentFromURL isn't there, then the API has changed or there's something else wrong, I've read through your code and it looks like you're doing all the same things I have.
I don't believe that the dir() of the methods on the desktop object will be useful, as I think there's a __getattr__ method being used to proxy through the requests, and all the methods you've printed out are utility methods used for the stand-in object for the com.sun.star.frame.Desktop.
I think perhaps the failure could be that there's no method named loadComponentFromURL that has exactly 1 argument. Perhaps giving the 4 argument version will result in the method being found and used. This could simply be an impedance mismatch between Python and Java, where Java has call-signature method overloading.
This looks like issue 90701: http://www.openoffice.org/issues/show_bug.cgi?id=90701
See also http://piiis.blogspot.com/2008/10/pyuno-broken-in-ooo-30-with-system.html and http://udk.openoffice.org/python/python-bridge.html
I'm relatively new to programming/python, so I'd appreciate any help I can get. I want to save an excel file as a specific format using Excel through COM. Here is the code:
import win32com.client as win32
def excel():
app = 'Excel'
x1 = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = x1.Workbooks.Add()
sh = ss.ActiveSheet
x1.Visible = True
sh.Cells(1,1).Value = 'test write'
ss.SaveAs(Filename="temp.xls", FileFormat=56)
x1.Application.Quit()
if __name__=='__main__':
excel()
My question is how do I specify the FileFormat if I don't explicitly know the code for it? Browsing through the documentation I find the reference at about a FileFormat object. I'm clueless on how to access the XlFileFormat object and import it in a way that I can find the enumeration value for it.
Thanks!
This question is a bit stale, but for those reaching this page from Google (as I did) my solution was accessing the constants via the win32com.client.constants object instead of on the application object itself as suggested by Eric. This lets you use enum constants just like in the VBE:
>>> import win32com.client
>>> xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
>>> C = win32com.client.constants
>>> C.xlWorkbookNormal
-4143
>>> C.xlCSV
6
>>> C.xlErrValue
2015
>>> C.xlThemeColorAccent1
5
Also, unless you've manually run the makepy utility, the constants may not be available if initializing the application with the regular win32com.client.Dispatch(..) method, which was another issue I was having. Using win32com.client.gencache.EnsureDispatch(..) (as the questioner does) checks for and generates the Python bindings at runtime if required.
I found this ActiveState page to be helpful.
When I used COM to access quickbooks, I could reach the constants defined under a constants member of the object. The code looked something like this (you'll be intersted in the third line):
self._session_manager.OpenConnection2("",
application_name,
QBFC8Lib.constants.ctLocalQBD)
I'm not sure if this will work, but try this:
import win32com.client as win32
def excel():
app = 'Excel'
x1 = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = x1.Workbooks.Add()
sh = ss.ActiveSheet
x1.Visible = True
sh.Cells(1,1).Value = 'test write'
ss.SaveAs(Filename="temp.xls", FileFormat=x1.constants.xlWorkbookNormal)
x1.Application.Quit()
if __name__=='__main__':
excel()
Replace xlWorkbookNormal with whatever format your trying to choose in the X1FileFormat web page you posted in your question.
All of the file format constants are documented here
As a general rule I find it really useful to pre-record any code in the VBA IDE in Excel. This way you can find out all the values of constants etc that you need to use within your python code. You can also make sure stuff will work from within a more controlled environment.