社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python中的openpyxl delete_rows函数用于断开合并单元格

Otsuki Takaya • 5 年前 • 2413 次点击  

我在Python3中使用openpyxl 2.6.0(与Django一起)。

我想操作我的excel skelton工作表(合并了一些单元格)来删除一行。但删除行后,合并的单元格不再合并。

即使删除了某些行,我也要保留合并的单元格。

代码和excel示例如下。

def excelsample(request):

    wb = openpyxl.load_workbook(os.path.join(settings.BASE_DIR, 'static', 'excel', 'sample.xlsx'))

    sheet = wb['Sheet1']
    sheet.delete_rows(6) # delete 6th row

    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="{fn}"'.format(fn=urllib.parse.quote("excelsample.xlsx"))

    wb.save(response)

    return response

之前:

enter image description here

enter image description here

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54632
 
2413 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Stephen Rauch
Reply   •   1 楼
Stephen Rauch    6 年前

有一个 issue 在openpyxl的bug追踪器上。它已被标记为无效。

最基本的问题是,要使其正常工作,所有合并的单元格区域都需要在删除行之后进行检查和更新。有几个性质类似的复杂/困难问题被认为是最小价值的,因此没有得到执行。

merged_cells )在行删除后可以更新的工作表上。

代码:

def delete_row_with_merged_ranges(sheet, idx):
    sheet.delete_rows(idx)
    for mcr in sheet.merged_cells:
        if idx < mcr.min_row:
            mcr.shift(row_shift=-1)
        elif idx <= mcr.max_row:
            mcr.shrink(bottom=1)

wb = openpyxl.load_workbook('csvfile.xlsx')

sheet = wb['Sheet2']
delete_row_with_merged_ranges(sheet, 6)

wb.save('csvfile2.xlsx')