【问题标题】:Insert column using openpyxl使用 openpyxl 插入列
【发布时间】:2013-04-05 05:06:39
【问题描述】:

我正在编写一个修改现有 Excel 文档的脚本,我需要能够在其他两个列之间插入一列,例如 VBA 宏命令 .EntireColumn.Insert

openpyxl 有什么方法可以插入这样的列吗?
如果没有,写一篇有什么建议吗?

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    这是一个更快的方法的示例:

    import openpyxl
    
    wb = openpyxl.load_workbook(filename)
    sheet = wb.worksheets[0]
    # this statement inserts a column before column 2
    sheet.insert_cols(2)
    wb.save("filename.xlsx")
    

    【讨论】:

    • 必须使用openpyxl 2.5或以上版本。
    • 如何在新列中插入数据数组?
    • 这对我有用,谢谢
    【解决方案2】:

    在 openpyxl 中没有找到像 .EntireColumn.Insert 这样的东西。

    我首先想到的是通过修改工作表上的 _cells 来手动插入列。我认为这不是插入列的最佳方式,但它有效:

    from openpyxl.workbook import Workbook
    from openpyxl.cell import get_column_letter, Cell, column_index_from_string, coordinate_from_string
    
    wb = Workbook()
    dest_filename = r'empty_book.xlsx'
    ws = wb.worksheets[0]
    ws.title = "range names"
    
    # inserting sample data
    for col_idx in xrange(1, 10):
        col = get_column_letter(col_idx)
        for row in xrange(1, 10):
            ws.cell('%s%s' % (col, row)).value = '%s%s' % (col, row)
    
    # inserting column between 4 and 5
    column_index = 5
    new_cells = {}
    ws.column_dimensions = {}
    for coordinate, cell in ws._cells.iteritems():
        column_letter, row = coordinate_from_string(coordinate)
        column = column_index_from_string(column_letter)
    
        # shifting columns
        if column >= column_index:
            column += 1
    
        column_letter = get_column_letter(column)
        coordinate = '%s%s' % (column_letter, row)
    
        # it's important to create new Cell object
        new_cells[coordinate] = Cell(ws, column_letter, row, cell.value)
    
    ws._cells = new_cells
    wb.save(filename=dest_filename)
    

    我知道这个解决方案非常丑陋,但我希望它能帮助您朝着正确的方向思考。

    【讨论】:

    • 这看起来应该没问题。我将使用的工作表最多只有几百行,我只需要插入两列,所以这应该可以完美地工作。将立即实施。谢谢!
    • 虽然这行得通,但值得注意的是,它在很大程度上取决于会发生变化的内部结构。该代码也与 Python 3 不兼容。有关更广泛的解决方案,请参阅bitbucket.org/snippets/openpyxl/qyzKn
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    相关资源
    最近更新 更多