How to draw a chart with excel using python? - 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

Related

Programmatically debug excel vba module using python

Is there a way to set a breakpoint and programmatically an excel vba module using pywin32? So far, I've been able to connect to an open instance of excel, add a workbook, add a vba module and then inject from a text file into this module.
import win32com.client as win32
excel = win32.Dispatch("Excel.Application") # generates a com instance
excel.Visible = True
workbook = excel.Workbooks.Add()
xlmodule = workbook.VBProject.VBComponents.Add(1)
with open('test.bas') as fo:
xlmodule.CodeModule.AddFromString(fo.read())
print('don')
I'm not sure how to then go about adding a breakpoint and then debug the module line by line. I know that XL.Application.Run can run the module for me, but I actually want to debug it through python. Any ideas?
Edit
Upon requests in the comments, here's my unfortunate, but nevertheless very common use case:
I have a legacy macro-enabled spreadsheet which I would like to convert to python using some form of test-driven approach. I use pywin32 to connect to the COM representations of the modules and run them. I use pytest to compare against my own python-based functions to ensure I am replicating the results accurately.
The missing, yet crucial, piece is code coverage. According to this link there are currently no code coverage tools for VBA modules. I need a way to circumvent this. If I can run my pywin32 based test suite and track which lines are being run by connecting to the VBA debugger, I may be able to do some crude, albeit slow, code coverage assessments.

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

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/

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.

Excel Python API

Does anyone know of a way of accessing MS Excel from Python? Specifically I am looking to create new sheets and fill them with data, including formulae.
Preferably I would like to do this on Linux if possible, but can do it from in a VM if there is no other way.
xlwt and xlrd can read and write Excel files, without using Excel itself:
http://www.python-excel.org/
Long time after the original question, but last answer pushed it top of feed again. Others might benefit from my experience using python and excel.
I am using excel and python quite bit. Instead of using the xlrd, xlwt modules directly, I normally use pandas. I think pandas uses these modules as imports, but i find it much easier using the pandas provided framework to create and read the spreadsheets. Pandas's Dataframe structure is very "spreadsheet-like" and makes life a lot easier in my opinion.
The other option that I use (not in direct answer to your problem) is DataNitro. It allows you to use python directly within excel. Different use case, but you would use it where you would normally have to write VBA code in Excel.
there is Python library to read/write Excel 2007 xlsx/xlsm files http://pythonhosted.org/openpyxl/
I wrote python class that allows working with Excel via COM interface in Windows http://sourceforge.net/projects/excelcomforpython/
The class uses win32com to interact with Excel. You can use class directly or use it as example. A lot of options implemented like array formulas, conditional formatting, charts etc.
It's surely possible through the Excel object model via COM: just use win32com modules for Python. Can't remember more but I once controlled the Media Player through COM from Python. It was piece of cake.
Its actually very simple. You can actually run anything from any program. Just see a way to reach command prompt from that program. In case of Excel, create a user defined function by pressing Alt+F11 and paste the following code.
Function call_cmd()
Shell "CMD /C Notepad", vbNormalFocus
End Function
Now press ctrl+s and go back to Excel, select a cell and run the function =call_cmd(). Here I ran Notepad. In the same way, you can see where python.exe is installed and run it. If you want to pass any inputs to python, then save the cells as file in local directory as csv file and read them in python using os.system().

Categories