openpyxl-在具有合并单元格的excel文件中添加新行 [英] openpyxl - adding new rows in excel file with merged cell existing

查看:756
本文介绍了openpyxl-在具有合并单元格的excel文件中添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前

之后

所以,我试图在excelsheet中添加6行. 我用 openpyxl.worksheet.worksheet.Worksheet.insert_rows(ws,idx = 0,amount = 6) 帮助我完成任务. 该行适用于普通的excel文件.

So, I was trying to add 6 rows into the excelsheet. And I used openpyxl.worksheet.worksheet.Worksheet.insert_rows(ws,idx=0,amount=6) to help me accomplish the task. This line works perfect with normal excel file.

但是,在excel文件中包含合并的单元格.该程序将无法正常工作,就像我附加的图像一样.

But, when it comes to the excel file contained merged cells. The program will not working properly just like the image I attached.

有人可以给我一些有关如何解决此问题的想法.我花光了所有的想法,需要一些启发.

Could someone give me some ideas about how to solve the issue. I ran out all the ideas and need some inspirations.

非常感谢谁回答我的问题!

Thank you very much for whoever answers my questions!!

推荐答案

假设您要在表格顶部添加3行,则首先需要向下移动合并的单元格,然后插入这些行; 为此,我们将使用shift(col_shift=0, row_shift=0)方法;

Let's say you want to add 3 rows at the top of your table, you'll first have to shift down the merged cells and then insert the rows; For this we are going to use the shift(col_shift=0, row_shift=0) method;

Help on method shift in module openpyxl.worksheet.cell_range:

shift(col_shift=0, row_shift=0) method of openpyxl.worksheet.cell_range.CellRange instance
    Shift the range according to the shift values (*col_shift*, *row_shift*).

    :type col_shift: int
    :param col_shift: number of columns to be moved by, can be negative
    :type row_shift: int
    :param row_shift: number of rows to be moved by, can be negative
    :raise: :class:`ValueError` if any row or column index < 1


要插入的行数必须与移动的行数一致; 因此,对于您的示例,您只需要:


The number of rows you want to insert must coincide with the numbers of rows you shift; So for your example you'll just have to:

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

所以最后合并的单元格被保留了

So in the end the merged cells are preserved

这篇关于openpyxl-在具有合并单元格的excel文件中添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆