使用openpyxl插入列

时间:2013-04-05 05:06:39

标签: python excel openpyxl

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

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

2 个答案:

答案 0 :(得分:11)

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

    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")

答案 1 :(得分:8)

在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)

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