我正在使用现有数据写入电子表格。在写入数据之前,我需要删除特定单元格范围内的数据。这是特别难以实现的。我在以下链接中尝试了未成功的解决方案。如果您有这方面的经验,将不胜感激。
选择工作表的代码:
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
VBA 有一个简单的命令。当然必须有一个等价的:
Worksheets("tmp").Range("A11:G1000").Clear
谢谢
最佳答案
我建议使用 pandas,如果你想删除单元格内的内容,你可以用 np.nan 填充它。我会这样做:
df = pd.read_excel('location_to_file.xlsx') #Here we read the excel
df.iloc[11:1001,:8] = np.nan #Here we are selecting from the first column upto the seventh (G) and from the 11th row up to the 1000 and making the values null.
df.to_excel('location_of_new_file.xlsx') #Here we are saving the excel with the modifications we made.
关于Python:是否可以在不逐个单元格迭代的情况下删除一系列excel单元格中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65793614/