2013-04-05 137 views
7

我正在處理一個修改現有excel文檔的腳本,我需要能夠在兩個其他列之間插入列,如VBA宏命令.EntireColumn.Insert使用openpyxl插入列

有沒有用openpyxl插入這樣一列的方法?
如果不是,有關寫作的建議?

回答

6

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

據我所知,這個解決方案是非常難看,但我希望它會幫助您在正確的方向思考。

+0

這看起來應該做得很好。我使用這個工作表的最多隻有幾百行,而且我只需要插入兩列,所以這應該完美。馬上執行此操作。謝謝! – Shawn 2013-04-05 15:18:40

+1

儘管這樣做有效,但值得注意的是它很大程度上依賴於會改變的內部結構。該代碼也與Python 3不兼容。有關更廣泛的解決方案,請參閱https://bitbucket.org/snippets/openpyxl/qyzKn – 2015-07-06 07:14:59