簡體   English   中英

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

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

我有3個參數。

startLine,starColumn和width(此處為2,8,3)

擅長

如何在不將空白寫入每個單元格的情況下擦除所選區域? (這里只有30條線,但可能有10000條線)

現在,我成功地計算了行數,但無法找到如何選擇和刪除區域的方法

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:代碼有效,我可能已經忘記了某些部分,因為它確實存在復制/粘貼錯誤,實際上,excel文件的處理由相互繼承的幾個類管理

謝謝

我通常要做的是在Excel中記錄宏,然后嘗試用Python重新破解VB。 對於刪除內容,我得到了類似的內容,應該不難將其轉換為Python:

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

在Python中,它應該類似於:

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

工作示例:

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()

這對我有用

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