Pywin32: How to import data into Excel?
Dmytro Lesnyak
Dmytro.Lesnyak at xtract.fi
Tue Nov 8 06:25:49 EST 2005
Thanks a lot. It really works!
Now, I can solve my problem and make my script faster!
> 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.
Yes, I also doing VBA macros first, but sometimes it is difficult for me
to translate it 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
Thanks. I got very good links
> 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>
Yes. It works. I wonder why I did not in my case.
It's strange, but if you put
xl.Visible = 1
after xl.Workbooks.OpenText("c:/temp/temp.txt")
It doesn't display the result. Probably, it is some Excel's feature :)
>+ 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>
I didn't know that. Probably, It would be faster.
> + 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/
Good option. Thanks :)
-Dima
More information about the Python-list
mailing list