簡體   English   中英

openpyxl-在具有合並單元格的excel文件中添加新行

[英]openpyxl - adding new rows in excel file with merged cell existing

之前

因此,我試圖將6行添加到excelsheet。 我使用openpyxl.worksheet.worksheet.Worksheet.insert_rows(ws,idx = 0,amount = 6)來幫助我完成任務。 該行適用於普通的excel文件。

但是,當談到excel文件時,包含合並的單元格。 該程序將無法正常工作,就像我附加的圖像一樣。

有人可以給我一些有關解決問題的想法。 我用盡了所有想法,需要一些啟發。

非常感謝誰回答我的問題!!

假設您要在表格頂部添加3行,首先必須向下移動合並的單元格,然后插入這些行; 為此,我們將使用shift(col_shift=0, row_shift=0)方法;

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

您要插入的行數必須與移動的行數一致; 因此,對於您的示例,您只需要:

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

因此最后合並的單元格得以保留 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM