Win32:Python 从 Excel 获取所有列名
Win32: Python to get all Column Names from Excel
如何使用 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 上,所以它似乎有可能......而且我在谷歌搜索时找不到任何结果:(
以下脚本向您展示了如何显示给定工作表的所有列标题。首先它计算使用的列数,然后枚举每一列。接下来它显示给定工作簿的所有命名范围,对于每个它都将实例存储到 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
.
的命名范围
如何使用 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 上,所以它似乎有可能......而且我在谷歌搜索时找不到任何结果:(
以下脚本向您展示了如何显示给定工作表的所有列标题。首先它计算使用的列数,然后枚举每一列。接下来它显示给定工作簿的所有命名范围,对于每个它都将实例存储到 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
.