使用Python填写包含数据验证下拉列表的Excel工作簿

2024-09-29 23:18:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Excel文件,其中包含通过数据验证创建的下拉列表

在第一张工作表中,我添加了可用的工人,然后从使用数据验证创建的第二张工作表的下拉列表中选择他们

Insert Workers

Insert workers

从下拉列表中选择工作者

Select workers from dropdown

现在,我想从Django应用程序中添加额外的工人。 我打开文件并用openpyxl对其进行编辑

import openpyxl
wb = openypy.load_workbook('/home/michal/Project.xlsx')
ws = wb['Workers']
ws['A8'].value = 'Eve'
wb.save('/home/michal/Project/saved.xlsx')

这样做我就失去了从下拉列表中选择值的能力

原因是openpyxl没有加载工作表之间的数据连接。 我们可以看到比较文件中包含的xml

原始文件

    <mergeCells count="3">
        <mergeCell ref="A3:B3"/>
        <mergeCell ref="A13:B13"/>
        <mergeCell ref="A23:B23"/>
    </mergeCells>
    <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
    <extLst>
        <ext uri="{CCE6A557-97BC-4b89-ADB6-D9C93CAAB3DF}"
             xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main">
            <x14:dataValidations count="1" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">
                <x14:dataValidation type="list" allowBlank="1" showInputMessage="1" showErrorMessage="1"
                                    xr:uid="{B93E0E6F-3CDC-46D6-AB87-8FB207C05210}">
                    <x14:formula1>
                        <xm:f>Workers!$A$2:$A$20</xm:f>
                    </x14:formula1>
                    <xm:sqref>B4:B8 B14:B18 B24:B28</xm:sqref>
                </x14:dataValidation>
            </x14:dataValidations>
        </ext>
    </extLst>
</worksheet>

使用openpyxl编辑的

    <mergeCells count="3">
        <mergeCell ref="A3:B3"/>
        <mergeCell ref="A13:B13"/>
        <mergeCell ref="A23:B23"/>
    </mergeCells>
    <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
</worksheet>

xlsx xml文件中的任何更改都会导致文件或工作表损坏

是否有一种在文件之间复制未更改的工作表XML的有效方法,或者您是否知道有哪个库能够加载具有extLst节点的完整工作簿。 我从Ubuntu服务器上的Django应用程序运行这个脚本,因此无法使用xlwings


Tags: 文件数据ref列表countxlsxworkers工人

热门问题