python和excel之间的python com [英] Python com between python and excel
问题描述
我正在尝试学习一些python,并且希望python使用win32模块与excel进行交互。我在Wiki 此处上找到了一个基本示例。
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....
推荐答案
您链接的代码看起来就像是直接从此博客中提取的一样。从它的声音来看,您不是要与 Softimage 。
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.
此外,如果您使用的是Excel 2007或更高版本,则要写入 xlsx
文件,因为这就是 Excel.Application
将为您创建的文件。
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
这篇关于python和excel之间的python com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!