简体   繁体   English

使用 Python openpyxl 修改 Excel 文件中的命名表

[英]Modify Named Table in Excel File with Python openpyxl

I want to add columns to an existing table in an excel file.我想将列添加到 excel 文件中的现有表。 Therefore I wan't to use python and the openpyxl library.因此我不想使用 python 和 openpyxl 库。

Right now I use a class when it is initialising, it is connecting to the file.现在我在初始化时使用 class,它正在连接到文件。 Afterwards I call the check_for_column function and when the column is not existing it should create it.之后我调用 check_for_column function 并且当该列不存在时它应该创建它。 And in the end of the script I save the file.在脚本的末尾,我保存了文件。


import os
from openpyxl import load_workbook
from openpyxl.worksheet.table import Table, TableColumn, range_boundaries
from openpyxl.utils.cell import get_column_letter


class ExcelHandler:
    _wb_name = None
    _table = None
    _wb = None

    def __init__(self):
        self._wb_name = os.getenv('EXCEL_FULLPATH')
        self._wb = load_workbook(filename=self._wb_name, keep_vba=True)
        sheet = self._wb['DataInbox']
        self._table = sheet.tables['WebPageForms']
        return

    def check_for_column(self, column_name):

        if not column_name in self._table.column_names:
            lst_ids = [my_object.id for my_object in self._table.tableColumns]
            new_id = lst_ids[-1]+1

            # change range of table
            min_col, min_row, max_col, max_row = range_boundaries(
                self._table.ref)
            max_col += 1
            mx = get_column_letter(max_col)
            mn = get_column_letter(min_col)
            self._table.ref = '{}{}:{}{}'.format(mn, min_row, mx, max_row)

            # add column to table
            tc = TableColumn(id=new_id, name=column_name)
            self._table.tableColumns.append(tc)

        return

    def save_wb(self):
        self._wb.save(self._wb_name)
        return

The code runs fine as shown.如图所示,代码运行良好。 Although when I then try to open the file with excel it gives me an alert saying:尽管当我随后尝试使用 excel 打开文件时,它给了我一条警告:

We found a problem with some content in 'file.xlsm'.我们发现“file.xlsm”中的某些内容存在问题。 Do you want us to try to recover as much as we can?你想让我们尽可能地恢复吗? If you trust the source of this workbook, click Yes.如果您信任此工作簿的来源,请单击“是”。

This is the repair result of excel when I press yes这是excel按yes的修复结果

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>Repair Result to file.xml</logFileName><summary>Errors were detected in file ’*path*/file.xlsm’</summary><repairedRecords summary="Following is a list of repairs:"><repairedRecord>Repaired Records: Table from /xl/tables/table1.xml part (Table)</repairedRecord></repairedRecords></recoveryLog>

I would highly appreciate If anyone could help me如果有人能帮助我,我将不胜感激

Ok, I found the problem why the excel file is corrupt, my bad.好的,我找到了 excel 文件损坏的问题,我的错。 when I create the column in the table, I also have to write the name in the respective cell:当我在表中创建列时,我还必须在相应的单元格中写下名称:

    def check_for_column(self, column_name):

            ***

            # write name in cell of new column header
            self._ws.cell(row=min_row, column=max_col).value = column_name

            ***

        return

If I add this to the code, my table is modified correctly如果我将此添加到代码中,我的表将被正确修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM