Win32:Python从Excel中获取所有列名称
如何从Excel工作表中使用COM接口(即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所以它似乎以某种方式是可能的…此外,我无法find任何结果时googeling 🙁
以下脚本显示如何显示给定工作表的所有列标题。 首先计算使用的列数,然后枚举每列。 接下来,它会显示给定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
的命名区域。
- 在C#中为Excel自动化创buildCOM对象时发生COMException
- Excel将string数据截断为255个符号。 如何在不更改registry的情况下读取整个string数据
- 从MemoryStream运行Microsoft Excel应用程序
- 在Excel中正确处理Excel COM对象添加
- 在Excel中访问数据 – 来自python的Reuter
- C#Excel自动化导致Excel内存泄漏
- 在未安装MS Office的计算机上使用Office.Interop.Excel
- 当我将其设置为activeworkbook时,为什么我的Workbook对象为空?
- 使用PowerShell从Excel文件读取注释