Search code examples
pythonopenpyxl

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.sstatic.net/hl5QY.png

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


Solution

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

    Before enter image description here

    After enter image description here

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