使用^{VARIANT
类型:
# RANGE(“C14:D21”) has values
# Setting the Value on the Range with a Variant should work, but
# list or tuple is not getting converted properly it seems
>>>from comtypes.client import CreateObject
>>>xl = CreateObject("Excel.application")
>>>xl.Workbooks.Open(r'C:\temp\my_file.xlsx')
>>>xl.Visible = True
>>>vals=tuple([(x,y) for x,y in zip('abcdefgh',xrange(8))])
# creates:
#(('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('g', 6), ('h', 7))
>>>sheet = xl.Workbooks[1].Sheets["Sheet1"]
>>>sheet.Range["C14","D21"].Value()
(('foo',1),('foo',2),('foo',3),('foo',4),('foo',6),('foo',6),('foo',7),('foo',8))
>>>sheet.Range["C14","D21"].Value[()] = vals
# no error, this blanks out the cells in the Range
根据comtypes
docs:
When you pass simple sequences (lists or tuples) as
VARIANT
parameters, the COM server will receive aVARIANT
containing aSAFEARRAY
ofVARIANT
s with the typecodeVT_ARRAY
|VT_VARIANT
.
这似乎与what MSDN says有关将数组传递到范围值的内联。我还发现this page在C中显示了类似的内容。有人能告诉我我做错了什么吗?
编辑
我想出了一个更简单的例子,其执行方式与此相同(在这方面,它不起作用):
>>>from comtypes.client import CreateObject
>>>xl = CreateObject("Excel.application")
>>>xl.Workbooks.Add()
>>>sheet = xl.Workbooks[1].Sheets["Sheet1"]
# at this point, I manually typed into the range A1:B3
>>> sheet.Range("A1","B3").Value()
((u'AAA', 1.0), (u'BBB', 2.0), (u'CCC', 3.0))
>>>sheet.Range("A1","B3").Value[()] = [(x,y) for x,y in zip('xyz',xrange(3))]
# Using a generator expression, per @Mike's comment
# However, this still blanks out my range :(
我花了很多时间试图找出解决这个问题的方法,以便能够完全用python代替matlab,在各种不同的论坛上阅读,却没有真正的直接答案。
这是我的健壮的解决方案,效果很好。我必须编写每天/每周/每月/季度的报告,这些报告经常写入xlsx,这个功能比使用python&com向xlsx写入的一些信息要好得多。
注: 我经常使用Numpy,因为它对于以我想编写的格式创建表非常有用,所以这是下面函数工作所必需的库。 我知道所有这些函数都可以组合起来创建一个类,但是由于这个函数是在脚本中调用的,并且它们对于将其创建为类并不是一个很大的好处,所以我没有这样做。
尝试
sheet.Range("C14", "D21").Value = vals
。我不太确定API是如何构造的,但它对我很有用。(而且,
tuple([(x,y) for x,y in zip('abcdefgh',xrange(8))])
可以替换为生成器表达式tuple((x, y) for x, y in zip('abcdefgh', xrange(8)))
,这似乎是一个更干净的习惯。在这种特殊情况下,只需列表理解[(x, y) for x, y in zip('abcdefgh', xrange(8))]
也可以。)相关问题 更多 >
编程相关推荐