【问题标题】:Python: Is it possible to delete values in a range of excel cells without iterating cell by cell?Python:是否可以在不逐个单元格迭代的情况下删除一系列excel单元格中的值?
【发布时间】: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
  1. 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 = ''
  1. 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
  1. https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.cell_range.html:这个链接讨论了如何引用一个范围,但从我读到的内容来看,它不允许设置这个范围内的单元格的值。

VBA 有一个简单的命令。当然必须有一个等价物:

Worksheets("tmp").Range("A11:G1000").Clear

谢谢

【问题讨论】:

    标签: python excel pandas range


    【解决方案1】:

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

    【讨论】:

    • 谢谢。这不起作用,因为我只删除文件中的一些数据。其余列的公式引用了我要粘贴的新数据。所以我无法创建新文件。
    • 你的想法把我引向了一个黑客。我可以用我想要的行和列创建一个带有 nans 的 df,然后将该数据粘贴到单元格中。会试试的。
    • 我也喜欢的另一个选项是将公式开头的字符 = 替换为 # 因此它是文本,然后您在 python 中进行更改并将其保存回来然后替换# 回到 =,这样你的公式就可以正常工作了。不需要新建文件,覆盖即可。
    • 这是一个很酷的技巧。我没有将公式引入我的数据框中。所以在这种情况下它不会起作用,但过去保留公式一直很痛苦。会试试这个。
    • 是的,这就是我在 excel 中和将数据导入熊猫之前的管理方式
    【解决方案2】:

    @Celius Stingher 的想法使我想到了以下 hack。它不优雅但有效。所以我会等待几天得到更好的答案,然后再接受这个:

    ws = 'tmp'
    
    # get start row and start col
    stcell = 'A11'
    cell= coordinate_to_tuple(stcell) # (function taken from here: https://openpyxl.readthedocs.io/en/stable/_modules/openpyxl/utils/cell.html)
    strow = cell[0]-1
    stcol = cell[1]-1
    
    # update sheet in writer
    writer.sheets = dict((ws.title, ws) for ws in wb.worksheets) #the writer was created originally in the code
    
    # check worksheet exists and make active
    for s in range(len(shts)):
        if wb.sheetnames[s] == ws:
            break
    wb.active = s
    sht = wb.active
    
    # delete old data in worksheet
    cols = len(dfPR.columns)  # get number of columns to overwrite from dataframe with the new data.
    df = pd.DataFrame(np.zeros([1000, cols])*np.nan) # creates a dummy df with nans
    df.to_excel(writer, sheet_name = ws, startrow = strow, startcol=stcol, index = False, header=False) # deletes data in first n cols.
    
    # write new data
    dfPR.to_excel(writer, sheet_name = ws, startrow = strow, startcol=stcol, index = False, header=False) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2014-05-08
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多