使用openpyxl插入列

Sha*_*awn 10 python excel openpyxl

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

是否有任何方法使用openpyxl来插入这样的列?
如果没有,有关写一个的建议吗?

小智 13

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

    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")
Run Code Online (Sandbox Code Playgroud)

  • 如何将数据数组插入到新列中? (3认同)
  • **重要提示**:以下列中的公式不会像在 Excel 中那样自动翻译。此外,后续列的格式和宽度也可能不会移动。 (2认同)

ale*_*cxe 8

没有.EntireColumn.Insert在openpyxl中找到任何东西.

首先想到的是通过修改工作表上的_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)
Run Code Online (Sandbox Code Playgroud)

我知道这个解决方案非常难看但我希望它能帮助你思考正确的方向.

  • 虽然这种方法有效,但值得注意的是,它在很大程度上取决于内部结构的变化。该代码也不兼容 Python 3。有关更广泛的解决方案,请参阅 https://bitbucket.org/snippets/openpyxl/qyzKn (2认同)