openpyxl 列 插入_使用openpyxl插入列

这篇博客介绍了如何在Python中使用openpyxl库手动插入Excel文件中的列,由于openpyxl没有直接提供类似VBA的EntireColumn.Insert功能,作者通过遍历和修改worksheet的cells来实现这一操作。提供的代码示例展示了插入新列的过程,并强调了这种方法虽然效率不高,但能够达到目的。
摘要由CSDN通过智能技术生成

I'm working on a script that modifies an existing excel document and I need to have the ability to insert a column between two other columns like the VBA macro command .EntireColumn.Insert.

Is there any method with openpyxl to insert a column like this?

If not, any advice on writing one?

解决方案

Haven't found anything like .EntireColumn.Insert in openpyxl.

First thought coming into my mind is to insert column manually by modifying _cells on a worksheet. I don't think it's the best way to insert column but it works:

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)

I understand that this solution is very ugly but I hope it'll help you to think in a right direction.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值