【发布时间】:2021-01-19 23:20:15
【问题描述】:
我正在使用现有数据写入电子表格。在写入数据之前,我需要删除特定单元格范围内的数据。这是特别难以实现的。我在以下链接中尝试了未成功的解决方案。如果您有这方面的经验,将不胜感激。
选择工作表的代码:
ws = 'tmp'
for s in range(len(shts)):
if wb.sheetnames[s] == ws:
break
wb.active = s
sht = wb.active
cell_range = eval('self.sht.Range(\self.sht.Cells%s, self.sht.Cells%s)' % \
("A11", "G1000"))
无法获取删除数据代码,因为范围选择本身提供了错误:
File "C:\Users\shefali\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3418, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-49-99fdfabfb7fa>", line 2, in <module>
("A11", "G1000"))
File "<string>", line 1
self.sht.Range(\self.sht.CellsA11, self.sht.CellsG1000)
^
SyntaxError: unexpected character after line continuation character
来自同一链接的另一个解决方案也不起作用:
sht.Range("A11", "G1000").Value = ''
stcell = 'A11'
# delete old data in worksheet
cols = len(dfPR.columns) # gets the number of columns to delete the data for.
sht.range(stcell, 'G1000').value=None
- https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.cell_range.html:这个链接讨论了如何引用一个范围,但从我读到的内容来看,它不允许设置这个范围内的单元格的值。
VBA 有一个简单的命令。当然必须有一个等价物:
Worksheets("tmp").Range("A11:G1000").Clear
谢谢
【问题讨论】: