[英]Converting .XLSX to .XLS in Python with win32com.client module
[英]What is the syntax in Python Win32com.Client module for Select-Case (excel)
因此,我正在嘗試有效刪除符合特定條件的Excel電子表格中的行。 但是,我認為如果我可以使用一些內置的VBA功能來選擇我要刪除的所有行,然后立即將它們全部刪除,那么它可能會更快。
以下鏈接是VBA相當於我想使用python win32com.client模塊做的事情: https ://stackoverflow.com/a/31390697/9453718
我目前正在循環並刪除行。 我瀏覽了excel中的所有行,如果符合某些標准,我會調用:Sheet.Rows(r).EntireRow.Delete()
有什么建議么?
編輯:這是我目前擁有的一個逐個刪除每一行的示例
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
book = excel.Workbooks.Open("ExcelWith200000Lines.xlsm")
sheet = book.Worksheets(0) #gets first sheet
nrows = sheet.UsedRange.Row + sheet.UsedRange.Rows.Count-1 # number of rows
ncols = sheet.UsedRange.Column + sheet.UsedRange.Columns.Count-1 # num of cols
data = sheet.Range('A1:'+NumToLetter(ncols) + str(nrows)).Value #loads all the data on the sheet into the python script
RELEVANT_COL_INDEX=0
for r in range(nrows-1, -1, -1): #starts at last row and goes to first row
if data[r][RELEVANT_COL_INDEX] == "delete_me":
sheet.Rows(r+1).EntireRow.Delete() #deletes the row here
book.SaveAs("myOutput.xlsm")
SELECT CASE
語句不是Excel對象庫的一部分,但它是VBA語言的一部分。 當您使用win32com
將Python作為COM接口連接到Excel時,您只能連接到Excel及其對象庫,包括其對象(工作簿,工作表,圖表等)及其屬性和方法。
實際上,VBA正是您在Python中所做的:與Excel對象庫的COM接口。 請參閱Tools \\ References下的內容,查找VBA通常是第一個選定的引用庫。 因此它不是 Excel的一部分。 選擇案例文檔並不表示任何Excel方法。 因此,您可以在MS Access VBA,Word VBA,Outlook VBA等中使用SELECT CASE
。
因此,在Python中使用類似版本的VBA的SELECT CASE
,這可能是多行if
和elif
語句。 雖然其他語言如Java,PHP和R維護switch
方法,但Python沒有這個。 請參閱Python中的switch語句的替換 。
請考慮以下使用鏈接的Excel問題的示例:
if not (xlwsh.Cells(i, 2) in [0.4, 0.045, 0.05, 0.056, 0.063, 0.071, 0.08, 0.09]
or xlwsh.Cells(i, 2) < 0):
xlwsh.Rows(i).EntireRow.Delete
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.