autofill - xlwings 和自动填充脚本
问题描述
我试图理解为什么一个脚本有效而另一个无效。他们都应该使用自动填充方法填充 excel 列范围。
下面的脚本(来自此处的 EuroMillions xlwings 教程)应该使用初始单元格中的公式自动填充 excel 列范围到最后一行:
脚本#1:
#script to fill a range given the first cell and the last row
def autofill(worksheet, cell, last_row):
rg_cell = worksheet.range(cell) #initial cell assignment
to_fill = "{col}{top_row}:{col}{last_row}".format(
col=rg_cell.get_address(0,0)[0],top_row=rg_cell.row,last_row=last_row) #fill range
rg_cell.api.Autofill(worksheet.range(to_fill).api, 0) #autofill
我不得不对上面的脚本进行重大更改,因为它对我不起作用。它将在 Jupyter 笔记本中无限期地运行而没有任何输出 (In[*])。
如果我中断内核引擎,则会生成以下输出:
---------------------------------------------------------------------
AttributeError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\xlwings\_xlwindows.py in __getattr__(self, item)
121 try:
--> 122 v = getattr(self._inner, item)
123 if isinstance(v, (CDispatch, CoClassBaseClass, DispatchBaseClass)):
~\AppData\Roaming\Python\Python37\site-packages\win32com\client\__init__.py in __getattr__(self, attr)
483 if args is None:
--> 484 raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
485 return self._ApplyTypes_(*args)
AttributeError: '<win32com.gen_py.Microsoft Excel 16.0 Object Library.Range instance at 0x1406515641608>' object has no attribute 'Autofill'
During handling of the above exception, another exception occurred:
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-44-a0a426ef3f0a> in <module>
1 # call above script to fill
----> 2 my_autofill(frequencies,"B2",51)
<ipython-input-41-e531f839102a> in my_autofill(worksheet, cell, last_row)
7 last_row
8 )
----> 9 worksheet.range(cell).api.Autofill(worksheet.range(to_fill).api, 0)
C:\ProgramData\Anaconda3\lib\site-packages\xlwings\_xlwindows.py in __getattr__(self, item)
139 # we try to test to see what's going on really
140 try:
--> 141 self._oleobj_.GetIDsOfNames(0, item)
142 except pythoncom.ole_error as e:
143 if e.hresult != -2147418111: # RPC_E_CALL_REJECTED
KeyboardInterrupt:
下面是一个新脚本,它可以工作并执行上述脚本应该做的事情。下面的脚本使用连接而不是上面的 .format 方法。
脚本 #2
#my script to fill a range given the first cell and the last row
def my_autofill(wrksheet, start_cell, mylast_row): #arguments
myrange=start_cell + ":" + wrksheet.range(start_cell).get_address(0,0)[0]\
+ str(mylast_row) #define range using arguments
wrksheet.range(start_cell).api.AutoFill(wrksheet.range(myrange).api,0) #autofill
谁能帮助解释为什么第一个脚本不起作用?
解决方案
推荐阅读
- javascript - Javascript 测试引用相同的对象数组,即使我在每次测试之前都将其清空
- google-maps - 如何使用 google place API 仅获取没有国家/地区的城市名称
- sql - Postgresql中根据条件获取上一条记录
- node.js - 护照认证后无法获取任何视图
- python-3.x - 基于匹配的 XML 删除标签
- javascript - 如何从解析服务器获取父母及其孩子的条目?
- microsoft-cognitive - 将人脸数据从一个人组复制到另一个人组
- ruby-on-rails - 为 Ruby 应用程序迁移 Azure 数据库的问题
- scala - 这段带有嵌套期货的代码会造成死锁吗?
- go - 使用反射调用结构方法