试着写入下一行(python / win32com)

时间:2017-03-14 16:24:23

标签: 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将打印要写入的行号

1 个答案:

答案 0 :(得分:0)

无法对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