既存の Excel ドキュメントを変更するスクリプトに取り組んでおり、VBA マクロ コマンドのように他の 2 つの列の間に列を挿入する機能が必要.EntireColumn.Insert
です。
このような列を挿入するopenpyxlの方法はありますか?
そうでない場合、それを書くためのアドバイスはありますか?
.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)
この解決策が非常に醜いことは理解していますが、正しい方向に考えるのに役立つことを願っています.