Win32:Python从Excel

时间:2016-10-10 07:10:57

标签: python excel winapi com

如何使用COM接口从Excel工作表中获取所有已定义的名称,即Python中的Win32 API?

我想获得某种类型的词典,例如在下面的例子中,它将是:

cols['Stamm_ISIN'] = 2

这样我以后可以使用它的ID 2访问该列来设置一些值:excel.Cells(row, cols['Stamm_ISIN']).Value = 'x'

我有点困在API文档https://msdn.microsoft.com/en-us/library/office/ff841280.aspx所以它似乎在某种程度上是可能的...而且当googeling时我找不到任何结果:(

enter image description here

1 个答案:

答案 0 :(得分:1)

以下脚本显示如何显示给定WorkSheet的所有列标题。首先,它计算使用的列数,然后枚举每列。接下来,它显示给定WorkBook的所有命名范围,每个范围都将实例存储到cols字典中。然后,可以将其与Range()结合使用,将给定命名范围内的所有单元格设置为给定值:

import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r"test file.xlsx")
ws = wb.Worksheets("Sheet1")

cols = {}       # Dictionary holding named range objects

# Determine the number of columns used in the top row
xlToLeft = -4159
col_count = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

# Print each column heading
for col in range(1, col_count + 1):
    print "Col {}, {}".format(col, ws.Cells(1, col).Value)

# Enumerate all named ranges in the Workbook
for index in range(1, wb.Names.Count + 1):
    print "Workbook: ", wb.Names(index).Name, wb.Names(index).Value
    cols[wb.Names(index).Name] = wb.Names(index)

# Enumerate any named ranges in the current Worksheet
for index in range(1, ws.Names.Count + 1):
    print "Sheet: ", ws.Names(index).Name, ws.Names(index).Value

# Change all cells for a named range called "TestRange" to "TEST"
ws.Range(cols["TestRange"]).Value = "TEST"

# Save the changes 
wb.Save()
excel.Application.Quit()

在此示例中,您的Excel文件需要具有名为TestRange的命名范围。