简体   繁体   English

使用win32com和python删除Excel的一部分

[英]Erasing only a part of an excel with win32com and python

I have 3 parameters. 我有3个参数。

startLine, starColumn and width (here 2,8,3) startLine,starColumn和width(此处为2,8,3)

擅长

How can I erase the selected area without writing blanks in each cells? 如何在不将空白写入每个单元格的情况下擦除所选区域? (here there is only 30 line but there could potetialy be 10 000 lines) (这里只有30条线,但可能有10000条线)

Right now I'm succesfully counting the number of lines but I can't manage to find how to select and delete an area 现在,我成功地计算了行数,但无法找到如何选择和删除区域的方法

self.startLine = 2
self.startColumn = 8
self.width = 8

self.xl = client.Dispatch("Excel.Application")
self.xl.Visible = 1
self.xl.ScreenUpdating = False
self.worksheet = self.xl.Workbooks.Open("c:\test.xls")
sheet = self.xl.Sheets("data")

#Count the number of line of the record
nb = 0
while sheet.Cells(start_line + nb, self.startColumn).Value is not None:
    nb += 1

#must select from StartLine,startColumn to startcolum+width,nb
#and then erase

self.worksheet.Save()

ps : the code works, I may have forgotten some part due do copy/pas error, in reality the handling of the excel file is managed by several classes inheriting from each other ps:代码有效,我可能已经忘记了某些部分,因为它确实存在复制/粘贴错误,实际上,excel文件的处理由相互继承的几个类管理

thanks 谢谢

What I usually do is that I record macro in Excel and than try to re-hack the VB in Python. 我通常要做的是在Excel中记录宏,然后尝试用Python重新破解VB。 For deleting content I got something like this, should not be hard to convert it to Python: 对于删除内容,我得到了类似的内容,应该不难将其转换为Python:

Range("H5:J26").Select
Selection.ClearContents

In Python it should be something like: 在Python中,它应该类似于:

self.xl.Range("H5:J26").Select()
self.xl.Selection.ClearContents()

Working example: 工作示例:

from win32com.client.gencache import EnsureDispatch

exc = EnsureDispatch("Excel.Application")
exc.Visible = 1
exc.Workbooks.Open(r"f:\Python\Examples\test.xls")
exc.Sheets("data").Select()
exc.Range("H5:J26").Select()
exc.Selection.ClearContents()

this worked for me 这对我有用

xl = EnsureDispatch('Excel.Application') 
wb2=xl.Workbooks.Open(file)
ws=wb2.Worksheets("data")

ws.Range("A12:B20").ClearContents()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM