问题
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