Read Excel checkbox from Python

别来无恙 提交于 2020-05-17 06:43:50

问题


I want to read data from an Excel sheet from a Python script and fill an XML file using the data read. Unfortunately the Excel sheet/form contains checkboxes and drop down lists. I was unable to get the value of the drop down list from its cell with the code below.

import openpyxl

excel_document = openpyxl.load_workbook('name.xlsx', keep_vba=True)

name_sheet1 = excel_document.get_sheet_names()[0]
sheet1 = excel_document.get_sheet_by_name(name_sheet1)
cell = sheet1['D38']
print(cell.value)

Does somebody know a way to parse Excel elements like checkboxes and drop down lists with Python?


回答1:


Instead of a using a library that reads Excel files, you can use win32com to run Excel (assuming you have Windows and Excel on your machine). You can then use the VBA documentation to help you navigate through Excel.

I had to do this with spreadsheets that contained checkboxes that weren't tied to cells. All the checkboxes had default names (e.g. "Check Box 1"), so I searched for them by name.

from win32com.client import gencache

excel = gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r"C:\Temp\MySpreadsheet.xlsx")
ws = wb.Worksheets.Item(1)
print('Shape count: %s' % len(ws.Shapes))
for shape in ws.Shapes:
    if shape.Type == 8: # form control
        if 'Check Box' in shape.Name:
            print('%s: %s' % (shape.AlternativeText, shape.ControlFormat.Value))

Apparently, the values of the checkboxes are 1.0 (true) or -4146 (false).

You can easily get other information, such as the name of a worksheet or the value of a cell.

print(ws.Name)
print(ws.Range('C10'))


来源:https://stackoverflow.com/questions/48503568/read-excel-checkbox-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!