I think this question has been asked before but it's not clear, in the original question the user has provided excel.exe which is a windows executable extension and not for mac.
I need to open new Excel instance in Python on MAC.
which module should I import?
I'm a newbie I have completed learning python language, but have trouble understanding documentation.
If all you need to do is launch Excel, the best way to do it is to use LaunchServices to do it.
If you have PyObjC (which you do if you're using the Python that Apple pre-installs on 10.6 and later; otherwise, you may have to install it):
import Foundation
ws = Foundation.NSWorkspace.sharedWorkspace()
ws.launchApplication_('Microsoft Excel')
If not, you can always use the open tool:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
Either way, you're effectively launching Excel the same way as if the user double-clicked the app icon in Finder.
If you want to make Excel do something simple like open a specific document, that's not much harder. Look at the NSWorkspace or open documentation to see how to do whatever you want.
If you actually want to control Excel—e.g., open a document, make some changes, and save it—you'll want to use its AppleScript interface.
Apple's recommended way of doing that is via ScriptingBridge, or using a dual-language approach (write AppleScripts and execute them via NSAppleScript—which, in Python, you do through PyObjC). However, I'd probably use appscript (get the code from here). Despite the fact that it's been abandoned by its original creator, and is only being sparsely maintained, and will probably eventually stop working with some future OS X version, it's still much better than the official solutions.
Here's a sample (untested, because I don't have Excel here):
import appscript
excel = appscript.app('Microsoft Excel')
excel.workbooks[1].column[2].row[2].formula.set('=A2+1')
From the comments it is not completely clear if you need to 'update' an Excel file with data, and just assume that you need Excel to do so, or that you need to change some excel files to include new data.
It is usually much easier, and certainly faster (wrt excution speed) to go with 'updating' an Excel file without starting Excel. However updating is not the right word: you have to read in the file and write it out new. You can of course overwrite the orginal file, so it looks like an update.
For 'updating' you can use the trio xlrd, xlwt, xlutils if the files you work with are .xls files (Excel 2003). IIRC xlwt does not support .xlsx for writing (but xlrd can read those files).
For .xlsx files I use openpyxl,
Both are good enough for writing things like data, formula and basic formatting.
If you have existing Excel files which you use as 'templates' with information that would get lost if you read/write using one of the above packages, then you have to go with updating the file in Excel. I had to do so because I had no easy way to include Visual Basic macros and very specific formatting specified by a client. And sometimes it is just easier to visually setup a spreadsheet and then just fill the cells programmatically. But this was all done on Windows.
If you really have to drive Excel on Mac, because you need to use existing files as templates, I suggest you look at Applescript. Or, if it is an option, look at OpenOffice/LibreOffice PyUno interface.
Related
I have currently written a Python script that uses UNO to interact with a LibreOffice .ods document. However, it is very unstable and is causing a lot of system errors and crashing on Ubuntu 17.04.
I read through the openpyxl docs but I can't find the answer to this quick question: Can I use openpyxl on Ubuntu to dynamically manipulate a .XLSX or a .ODS document with embedded formulas?
I.e. I want to open the document, read data from the cells, update the cell values in a loop, read the new output data from the document's own formulas, and then load this output into a numpy array and close the document without saving it.
Does Excel/libreoffice have to be installed for openpyxl to use the embedded formulas in this way?
Thank you
OpenPyXL doesn't need and cannot use a running instance of Excel. It doesn't interact with .ods at all. The closest thing to OpenPyXL for .ods is pyexcel-ods. The only practical way to evaluate Excel formulas is with a running instance of Excel. Likewise, the only practical way to evaluate LibreOffice formulas is with a running instance of LibreOffice.
So if you want to use OpenPyXL or pyexcel-ods "interactively", you would have to not use Excel/LibreOffice formulas but instead do all the calculations with Python.
If you need the formulas and you need to run it in Linux, then using UNO in some form (to control a running instance of LibreOffice) is probably still your best bet. Note that there are a few different Python interfaces to UNO, such as PyOO and UnoTools. I don't know what you're using now.
Finally, if the UNO-based methods are really too unstable, and you do have access to Excel, then you could try xlwings. It would be fairly convoluted to get this to run in Linux (it might require a virtual machine; testimonials for Excel under Wine have been mixed at best).
I would like to manipulate an Excel spreadsheet from Python, e.g. open it, and execute an embedded VBA macro, or some set of actions on the data inside. I have a choice of whether I would like to work on Windows or Linux for this.
There are packages ways to do this (xlwings package from this answer) but I am looking for something more native to explore what options are there.
I think one way to do this is the COM interface on Windows, which xlwings itself wraps. I found win32com python module, but seem to have very little documentation on manipulating particular objects, and what methods and attributes are available. Can someone please point me to a good information source (books are also ok)?
Alternatively, are there other options to do this, and if so, where can I read up on them?
I have gotten around this by using the Auto_Open() function in VBA, which runs when the Excel file opens.
Public Sub Auto_Open()
''' Run other macro here
End Sub
You could then open the Excel file using subprocess.popen. This is a bit of a hack, but avoids using win32com. I had to take this route because win32com wouldn't work on our locked down computers.
I am running a simulation that saves some result in a file from which I take the data I need and save it in
result.dat
like so:
SAN.statisticsCollector.Network Response Time
Min: 0.210169
Max: 8781.55
average: 346.966666667
I do all this using python, and it was easy to convert result.dat into an excel file using xlwt. The problem is that creating charts using xlwt is not possible. I than came across Jpype, but installation on my ubuntu 12.04 machine was a headache. I'm probably just being lazy but still - is there any other way, not necessarily python-related, to convert result.dat into an excel file with charts?
Thanks
P.s the file I want to create is a spreadsheet, not Microsoft's Excel!
there is a now a new possibility: http://pythonhosted.org/openpyxl/charts.html
and http://xlsxwriter.readthedocs.org/chart.html
The main problem is that currently there's no Python library that implements MS Excel chart creation, and, obviously, they will not appear due to lack of good chart format documentation (as python-excel.org guys told) and its huge complecity.
There are two other options though:
Another option is to use 3-rd party tools (like JPype that you've mentioned) combining them with Python scripts. As far as I know, except Java smartXML there's no libraries that are capable of creating excel charts (or course, there are ones for .NET, e.g. expertXLS) and I'm not sure it will run on Mono + IronPython, though you can try.
The third option is Win32 COM API, e.g. like described in this SO post, which is not quite an option for you due to your working operating system.
Was trying to use win32clipboard to do the copy paste operations for text (till now), and was able to do it with ease.But now am wondering how does the copy/paste operations would be accomplished for folders/files etc through that. I am using python to achieve the same. Could not also find any relevant formats for that. Is it something like file path gets copied and then paste operation identifies clipboard data as file path and then actually does the file copy? No clue :(.
Windows copy/paste stores things as OLE objects (http://en.wikipedia.org/wiki/Object_Linking_and_Embedding)
You need a python package to deal with OLE. This thread might help- How do I script an OLE component using Python?
When you copy a shell object (e.g. a file or a folder) to the clipboard, the shell places data into the clipboard in a variety of different formats. The clipboard viewer for such an operation shows the following formats:
I honestly don't know which one is used when you subsequently paste, but my guess would be the Shell IDList Array. The point is that the files and folders don't go into the clipboard, only references to them.
I believe that there is comprehensive documentation of this on MSDN: Shell Clipboard Formats.
That should give you enough orientation to conduct a further web search for Python wrappers to such functionality (I'm sure they will exist)!
i just installed python
i am trying to run this script:
import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
print row
i am running on windows.
do i have to type each line individually into python shell or can i save this code into a text file and then run it from the shell?
where does some.csv have to be in order to run it? in the same c:\python26 folder?
what is this code supposed to do?
Yes, you can create a file. The interactive shell is only for learning syntax, etc., and toying with ideas. It's not for writing programs.
a. Note that the script must have a .py extension, e.g., csvprint.py. To run it, you enter python csvprint.py. This will try to load csvprint.py from the current directory and run it.
The some.csv file has to be in the current working directory, which doesn't have to be (in fact, almost never should be) in the Python folder. Usually this will be you home directory, or some kind of working area that you setup, like C:\work. It's entirely up to you, though.
Without knowing the csv module that well myself, I'm guessing it reads CSV separated values from the file as tuples and prints each one out on the console.
One final note: The usual way to write such logic is to take the input from the command-line rather than hard-coding it. Like so:
import csv
reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
print row
And run it like so:
python csvprint.py some.csv
In this case you can put some.csv anywhere:
python csvprint.py C:\stuff\csvfiles\some.csv
When you have IDLE open, click File > New Window. (Or hit Ctrl + N)
This opens up a new window for you that's basically just a text editor with Python syntax highlighting. This is where you can write a program and save it. To execute it quickly, hit F5.
You can do both! To run the code from a text file (such as 'csvread.py', but the extension doesn't matter), type: python csvread.py at the command prompt. Make sure your PATH is set to include the Python installation directory.
"some.csv" needs to be in the current directory.
This code opens a Python file descriptor specifically designed to read CSVs. The reader file descriptor then prints out each row of the CSV in order. Check the documentation out for a more detailed example: http://docs.python.org/library/csv.html
Type the code into a *.py file, and then execute it.
I think the file should be in the same folder as your *.py script.
This opens a file stored in comma separated value format and prints the contents of each row.
All import does "Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the only way". The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it. The lack of a standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
The CSV module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats. All your code is doing is looping through that file.