Pywin32: How to import data into Excel?
Tim Golden
tim.golden at viacom-outdoor.co.uk
Tue Nov 8 05:46:50 EST 2005
[Dmytro Lesnyak]
> I need to import some big data into Excel from my
> Python script. I have TXT file (~7,5 Mb). I'm using
> Pywin32 library for that, but if I first try to read
> the TXT file and then save the values one by one like
> xlBook.Sheets(sheet_name).Cells(i,j).Value = value_from_TXT_file
> it takes about 10 hours to process whole data
A few suggestions:
+ When trying to automate anything in Excel, it's
usually illuminating to record a macro which does
what you want, and then to translate that VBA code
into Python.
+ To find documentation on the Microsoft object models,
MSDN is usually a good bet. Googling for:
site:msdn.microsoft.com excel object model
gives some hopeful-looking hits
+ I fiddled around for a few moments, and found that
the following code at least worked:
<code>
import win32com.client
xl = win32com.client.gencache.EnsureDispatch ("Excel.Application")
xl.Visible = 1
xl.Workbooks.OpenText ("c:/temp/temp.txt")
</code>
+ If you needed more control, bear in mind that you
can put lists and lists of lists directly into an
Excel range. So, something like this:
<code>
import win32com.client
a = [1, 2, 3]
b = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
xl = win32com.client.gencache.EnsureDispatch ("Excel.Application")
xl.Visible = 1
wb = xl.Workbooks.Add ()
ws = wb.ActiveSheet
ws.Range (ws.Cells (1, 1), ws.Cells (1, 3)).Value = a
ws.Range (ws.Cells (2, 1), ws.Cells (4, 3)).Value = b
</code>
+ Finally, you might look at PyExcelerator. I've toyed with
it only a little, but it seems to do the business, and
doesn't need Excel installed (so you can even run it on
Linux, if that takes your fancy). It's had a very recent
release, so it's definitely being maintained:
http://sourceforge.net/projects/pyexcelerator/
TJG
________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________
More information about the Python-list
mailing list