Python:是否可以在不逐个单元格迭代的情况下删除一系列excel单元格中的值?

标签 python excel pandas range

我正在使用现有数据写入电子表格。在写入数据之前,我需要删除特定单元格范围内的数据。这是特别难以实现的。我在以下链接中尝试了未成功的解决方案。如果您有这方面的经验,将不胜感激。
选择工作表的代码:

ws = 'tmp'
for s in range(len(shts)):
    if wb.sheetnames[s] == ws:
        break
wb.active = s
sht = wb.active
  • Setting an Excel Range with an Array using Python and comtypes?
  • 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 = ''
    
  • delete content of particular Excel cells python
  • 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
    
    谢谢

    最佳答案

    我建议使用 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/

    相关文章:

    python - 基于公共(public)列和索引的 Pandas 合并

    python - json 如何将 None 转储为空字符串

    python - Django 管理表单覆盖默认值

    vba使用另存为而不打开文件

    VBA 在范围内设置公式 - 问题

    python - 复制表 - Openpyxl : type object 'Workbook' has no attribute 'copy_worksheet'

    python - 从 CSV 文件创建图形并使用 Django 和 Pandas Python 库呈现到浏览器

    python - 如何获取空python数组中的dataFrame数组值

    python - "growing"(追加到)一个序列对象

    python - 如何增加表的大小?