Python com between python and excel

时光毁灭记忆、已成空白 提交于 2019-12-11 00:51:48

问题


I'm trying to learn some python and I wanted for python to interact with excel using the win32 module. I found a basic example online on wiki here.

It won't work however. This is the error I get.

Traceback (most recent call last):
  File "C:/Users/Greg/Desktop/python programming/excel2.py", line 8, in <module>
    sheet.Range("A2").Value = str(Application.SIFilter(None, c.siObjectFilter))
NameError: name 'Application' is not defined

My question is what does that line DO EXACTLY and why am I getting an error?

sheet.Range("A2").Value = str(Application.SIFilter(None, c.siObjectFilter))

import win32com.client
from win32com.client import constants as c

excel = win32com.client.Dispatch("Excel.Application")
book = excel.Workbooks.Add()
sheet = book.Worksheets(1)
sheet.Range("A1").Value = "Hello World!"
sheet.Range("A2").Value = str(Application.SIFilter(None, c.siObjectFilter))
book.SaveAs("c:\simple_example.xls")

sheet = None
book = None
excel.Quit()
excel = None

Thanks sorry if I'm super noob....


回答1:


The code you linked to looks like it's pulled straight off of this blog. From the sound of it, you're not trying to integrate with Softimage. You'll want to just take that line out.

Also, if you're working with Excel 2007 or later, you want to write to an xlsx file, because that's what Excel.Application is going to create for you.

Here's the same sample code modified with these changes.

import win32com.client

excel = win32com.client.Dispatch("Excel.Application")
book = excel.Workbooks.Add()
sheet = book.Worksheets(1)
sheet.Range("A1").Value = "Hello World!"
book.SaveAs("c:\simple_example.xlsx") # or .xls depending on version

sheet = None
book = None
excel.Quit()
excel = None



回答2:


In this line :

sheet.Range("A2").Value = str(Application.SIFilter(None, c.siObjectFilter))

you are trying to to turn Application.SIFilter(None, c.siObjectFilter) in to a string. You did not define the object called Application. I did not run the code, but I think it might work if you write excel.SIFilter(None, c.siObjectFilter). If you are just trying to learn, write something else, and you will get an excel file.



来源:https://stackoverflow.com/questions/10164621/python-com-between-python-and-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!