簡體   English   中英

嘗試寫到下一行(python / win32com)

[英]Trying to write to next line (python/win32com)

我能夠找到最后一行,並且設置了變量,但是卻出現此錯誤:該對象不支持枚舉

## Export Severity to Qualy Data ##
## access excel application and open active worksheet ##
Excel = win32.gencache.EnsureDispatch('Excel.application')
Excel.Visible = False
wb = Excel.Workbooks.Open('Qualys Data.xlsx')
sh = wb.ActiveSheet

## Find last row ##
lastRow = sh.UsedRange.Rows.Count
next_Row = lastRow+1
print("Next row to print: ", next_Row)

## Can i loop through the document, if on last_Row / print to last row?
for line in sh:
    if desired_row == next_Row:
        sh.Range("A1:A1").Value = reportDate

print("Exporting to data to new spreadsheet...")
time.sleep(1)

Excel.DisplayAlerts = 0
wb.SaveAs('Qualys Data.xlsx')
Excel.DisplayAlerts = True

Excel.Quit()

基本上我想寫到最后一行,如果在最后一行,next_Row將打印要寫入的行號

無法在wb.ActiveSheet上進行迭代,這就是您收到錯誤消息的原因。

如果您只是嘗試將一個單元格附加到第一行的底部,則可以直接寫入該單元格,而無需枚舉:

import win32com.client as win32
from datetime import datetime
import time

reportDate = datetime.now()

Excel = win32.gencache.EnsureDispatch('Excel.application')
Excel.Visible = False

wb = Excel.Workbooks.Open(r'e:\python temp\Qualys Data.xlsx')
ws = wb.ActiveSheet

## Find last row ##
lastRow = ws.UsedRange.Rows.Count
next_Row = lastRow + 1
print("Next row to print: ", next_Row)

ws.Cells(next_Row, 1).Value = reportDate

print("Exporting to data to new spreadsheet...")
time.sleep(1)

Excel.DisplayAlerts = 0
wb.SaveAs('Qualys Data.xlsx')
Excel.DisplayAlerts = True
Excel.Quit()

這是使用ws.Cells(next_Row, 1).Value = reportDate

在此示例中,它僅附加了當前日期和時間。


要將列表寫到最后一行,請使用以下命令:

data = ["cell 1", "cell 2", "cell 3", "cell 4"]
ws.Range(ws.Cells(next_Row, 1), ws.Cells(next_Row, len(data))).Value = data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM