Module that can help control excel from within python application anything more needed than pywin32? - python

I have a viewer I built using WXPython. The viewer is basically a browser (built on IE wx.lib.iewin) that loads the txt or htm files I have in a directory and then lets me move through the files sequentially. Instead of having to go to the directory to select the next file to view the viewer/browser has a next button that loads the next file in the queue.
I want to be able to add a new feature that allows me to highlight some text that is visible in the browser and then push a button and have that text passed into a cell in excel.
Lots of things are going to have to happen like I need to be able to find and start a new instance of excel. I need to be able to add a new worksheet and pass some values to populate cells on the worksheet based on the file I am looking at and then if I want to collect some data from the file I want to be able to highlight the data in the viewer and then press a button on the viewer and have the data passed to excel.
I think I am going to start with PyWin32 but I am wondering if there is something else I need but I don't know enough to look for it.
If someone knows of an example where text was piped from a Python application to excel under the users control I would appreciate a pointer in that direction. It is easy enough I think to do this going from the application to a file that gets created (but not displayed) but I am hoping to go from the browser to the excel file so that the user can evaluate their work in progress.

I'd recomend using one of the python excel modules like python-excel.
It works on any OS, and without any other Excel application installed.
http://www.python-excel.org/
Code would look somehting liek this to write to a new xls document, slightly different to open an existing.
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
# indexing is zero based, row then column
sheet.write(0,1,'test text')
wbk.save('test.xls')
Hopefully this can get you on the right path, then you'll be able to post more specific questions if you run into problems.
Note: Another option is openpyxl:
http://packages.python.org/openpyxl/tutorial.html

If you're using wxPython (which I assume you are due to the tag), you should look at XLSGrid: http://www.blog.pythonlibrary.org/2011/08/20/wxpython-new-widget-announced-xlsgrid/
If you just want to work with Excel, I would recommend xlwt or xlrd, although you can use PyWin32 to work with it too via COM: http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/

Related

Write data with Python into existing excel file keeping it intact as much as possible

We have a rather complicated Excel based VBA Tool that shall be replaced by a proper Database and Python based application step by step.
There will be time of the transition between were the not yet completely ready Python tool and the already existing VBA solution will coexist.
To allow interoperability the Python tool must be able to export the database values into the Excel VBA Tool keeping it intact. Meaning that not only all VBA codes have to work as expected but also Shapes, Special Formats etc, Checkboxes etc. have to work after the export.
Currently a simple:
from openpyxl import load_workbook
wb = load_workbook(r'Tool.xlsm', keep_vba=True)
# Write some data i.e. (not required to destroy the file)
wb["SomeSheet!SomeCell"] = "SomeValue"
wb.save(r"Tool_filled.xlsm")
will destroy the file, i.e. shapes won't work, checkboxes neither. (The resulting file is only 5 MB from originally 8 MB, showing that something went quite wrong).
Is there a way to only modify only the data of an ExcelSheet keeping everything else intact/untouched?
As far I know an Excel Sheet are only zipped .xml files. So it should be possible to edit only the related sheets? Correct?
Is there a more comfortable way as writing everything from scratch to only modify the data of an existing Excel file?
Note: The solution has to work in Linux, so simple remote Excel calls are not an option.

Using a macro to insert more macros

I've got some Python code that runs a query on a database that is read-only from my end and, which dumps me an Excel spreadsheet with relevant data that I want for visualization. I have several macros which process the data, create and edit graphs, and let me "filter" a couple different ways (each "filter" is several normal filters - convenient compared to manually selecting/clearing multiple filters).
My Python code generates a new Excel file daily stamped with the date. I would like to insert my suite of macros and run the setup ones automatically on each new file, rather than manually importing and executing them.
Is there a way to use a macro to insert several other macros, run some of them, and insert macro buttons or a dropdown box to run the filtering bit? If not, can it be done (or should it be done) from the Python side when it generates my Excel files?
Edit:
The python code was written by somebody else, and I do not know Python. It prints the data using:
with pd.ExcelWriter(filename) as writer:
df_merged_final.to_excel(writer, sheet_name='Final Data', index=False)
You can collect all your macros in a .bas file and import that whenever needed.
1) collect all your regular macros and put them in a module. You can even write one parent macro that calls all the other child macros, but they all need to be in this module;
2) export the module as a .bas file;
Then whenever you need the macros:
3) import the .bas file to your workbook;
4) your macros are now available in the ribbon of the developer tab which presents them as a dropdown list. If you used a parent macro, you can just click the parent macro to fire all the child macros.
This allows you to work in the source file itself and you can avoid copying large amounts of data to the clipboard. Also serves as a great backup of your most-used macros in case your master Excel file becomes corrupt.

How to draw a chart with excel using python?

Hi I intend to draw a chart with data in an xlsx file.
In order to keep the style, I HAVE TO draw it within excel.
I found a package named win32com, which can give a support to manipulate excel file with python on win32 platform, but I don't know where is the doc.....
Another similar question is how to change the style of cells, such as font, back-color ?
So maybe all I wanna know is the doc, you know how to fish is more useful than fishes.... and an example is better.
Check this lib, almost native excel graph can be generated here.
xlsxwriter line chart example
The only catch here is that you can't update the already existing sheet, means you can modify the sheet, with this lib you can create all most all the charts.
Documentation for win32com is next to non-existent as far I know. However, I use the following method to understand the commands.
MS-Excel
In Excel, record a macro of whatever action you intend to, say plotting a chart. Then go to the Macro menu and use View Macro to get the underlying commands. More often than not, the commands used would guide you to the corresponding commands in python that you need to use.
Pythonwin
You can use pythonwin to browse the underlying win32com defined objects (in your case Microsoft Excel Objects). In pythonwin (which can be found at \Lib\site-packages\pythonwin\ in your python installation), go to Tools -> COM Makepy Utility, select your required Library (in this case, Microsoft Excel 14.0 Object Library) and press Ok. Then when the process is complete, go to Tools -> COM Browser and open the required library under Registered Libraries. Note the ID no. as this would correspond to the source file. You can browse the various components of the library in the COM Browser.
Source
Go to \Lib\site-packages\win32com\ in your python installation folder. Run makepy.py and choose the required library. After this, the source file of the library can be found at \Lib\site-packages\win32com\gen_py . It is one of those files with the wacky name. The name corresponds to that found in Pythonwin. Open the file, and search for the commands you saw in the Excel Macro. (#2 and #3 maybe redundant, I am not sure)
AFAIK, win32com is an interface to Microsoft's COM technology, so you'd have to look there for an explanation of what objects and methods are available for the different COM-enabled applications. Your task will probably be easier if you don't start with an empty spreadsheet and try to create everything using win32com from scratch, but to create a template in Excel which only needs the actual data filled in. Actualy, since Excel can use ODBC data sources, maybe a database is an even better interface?
import win32com.client as w32
oe = w32.Dispatch("Excel.Application")
ow = oe.Workbooks.Add()
osh = ow.Sheets(1)
osh.Select()
osh.Activate()
osh.Cells(1,1).Font.Bold = True # set A1 to bold
osh.Range("A1").Interior.Color = RGB(255,0,0) # set to red background color

Is it possible create/edit an excel macro from python?

I'm currently working on a project that requires me to write a (seemingly endless) series of macros to reproduce pivot tables designed by one of our Analysts. The details change, but the code is largely the same from example to example.
I would like to programmaticly generate the vba code based on a handful of options and then add the macro to the given worksheet. Is it possible to create an excel macro with python using win32com or other? Is it possible to create an excel macro from another excel macro? Any other ideas?
Project Background, I have a python script that does the following:
pulls Google Analytic data
does various analysis
writes the results to excel
triggers a pre-written macro to turn the data into a beautifully formatted pivot table
emails it off to people who probably don't actually read it
Yes you can create an Excel macro with another Excel macro. For that to work, you need to tell Excel to Trust Access to the VBA Project Object model. (The setting is found in Macro Options in the Trust Center.) I don't know if you can do it from Python, but if you can, you probably also need to tell Excel it is ok.
For ease of coding, if you are doing this in Excel, add a reference to Micorsoft Visual Basic for Applications Extensibility.
You might also want to check out MZ-Tools 3.0 I find it very helpful for adding default\common code to a project.
On the other hand, your project sounds ripe for code reuse. If the common pivot table code is in one class/module, it is really easy to copy it from one open Excel project to another. (Just click and drag in the Project Explorer window.) You can also export it out to a text file and import it back in to another project later.

Embedding excel into a gui, for a python program

I'm writing a python(3) program that will run on windows only. The program should have a GUI that contains, in part of its window, an embedded excel workbook (and not just its data). Is there a way of doing so with wxPython/PyQt/other?
If not, I found a way of doing that in c#, so I thought of writing the GUI in c# and connect it to python with COM. Can I use IronPython to make a simpler connection? What are the pros and cons of using COM vs using IronPython?
Thanks in advance
One way would be to embed a web browser (QWebView) into the gui and then point it to your Excel Services. The primary issue here, and there are quite a few, is that you'll still need to use something like xlwt to manipulate the data. Unless you have a complex workbook (with macros etc) it might actually be easier to just do something like this using xlwt and xlrd:
value_1 = str(sheet.cell_value(sel,4))
self.lineEdit.setText(value_1)
You can use labels to add column and row names, lineEdits for values, and tabs for sheets. With a little ctrl+v action (or perhaps a "for I in foo") this wouldn't take as long as you might think.

Categories