使用openpyxl插入列
问题描述:
我正在处理一个修改现有excel文档的脚本,我需要能够在两个其他列之间插入列,如VBA宏命令.EntireColumn.Insert
。使用openpyxl插入列
有没有用openpyxl插入这样一列的方法?
如果不是,有关写作的建议?
答
在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)
据我所知,这个解决方案是非常难看,但我希望它会帮助您在正确的方向思考。
这看起来应该做得很好。我使用这个工作表的最多只有几百行,而且我只需要插入两列,所以这应该完美。马上执行此操作。谢谢! – Shawn 2013-04-05 15:18:40
尽管这样做有效,但值得注意的是它很大程度上依赖于会改变的内部结构。该代码也与Python 3不兼容。有关更广泛的解决方案,请参阅https://bitbucket.org/snippets/openpyxl/qyzKn – 2015-07-06 07:14:59