简体   繁体   中英

python openpyxl insert_cols changes merge-cells and styles

I tried to insert a column into an excel.

However, the style of cells has been changed

CODE:

import openpyxl

wb = openpyxl.load_workbook('xt3.xlsx')
sheet = wb.worksheets[0]

sheet.insert_cols(0)
[enter image description here][1]wb.save("filename.xlsx")

https://i.stack.imgur.com/hl5QY.png

issues on bitbucket: https://bitbucket.org/openpyxl/openpyxl/issues/1098/bugs-insert_cols-changes-merge-cells-and

This code will insert 3 columns; It keeps the background color but not all of the borders.

merged_cells_range = ws.merged_cells.ranges
for merged_cell in merged_cells_range:
    merged_cell.shift(3,0)
ws.insert_cols(1,3)

在此处输入图片说明

After some digging I wrote this code in openpyxl and xlrd/xlwt/xlutils. Support both xls and xlsx.

Before 在此处输入图片说明

After 在此处输入图片说明

The key is to use copy and generate coordinate. Code is here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM