简体   繁体   English

Python Openpyxl - 在 write_only 电子表格中添加列

[英]Python Openpyxl - Add column in write_only spreadsheet

I'm using Python and openpyxl library, but, I'm not able to use the insert_cols() function in openpyxl when my spreadsheet is in write_only=True mode.我正在使用 Python 和 openpyxl 库,但是当我的电子表格处于write_only=True模式时,我无法在 openpyxl 中使用insert_cols() function。 So, basically, I just want to add a new column to my spreadsheet when it's in write_only=True mode.所以,基本上,我只想在电子表格处于write_only=True模式时向它添加一个新列。

I'm able to use insert_cols() when loading the workbook by load_workbook() , but, not when I'm using the write_only mode.通过load_workbook()加载工作簿时,我可以使用insert_cols() ) ,但是,当我使用write_only模式时不能使用。 I have to use the write_only mode because my spreadsheets are quite large.我必须使用write_only模式,因为我的电子表格非常大。

Any ideas on how to add a new column are appreciated.任何关于如何添加新列的想法都值得赞赏。

Thank you.谢谢你。

This is my code:这是我的代码:

import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook(filename=r'path\myExcel.xlsx', read_only=True)
ws = wb['PC Details']

wb_output = Workbook(write_only=True)
ws_output = wb_output.create_sheet(title='PC Details')


for row in ws.rows:
    rowInCorrectFormat = [cell.value for cell in row]
    ws_output.append(rowInCorrectFormat)
    for cell in row:
        print(cell.value)

### THIS IS THE PART OF THE CODE WHICH DOES NOT WORK
ws_output.insert_cols(12)
ws_output['L5'] = 'OK or NOT GOOD?'
###

wb_output.save(r'path\test_Output_optimized.xlsx')

This is the exact error that I'm getting:这是我得到的确切错误:

ws_output.insert_cols(12)
AttributeError: 'WriteOnlyWorksheet' object has no attribute 'insert_cols'

The problem here lies in the flag write_only = True .这里的问题在于标志write_only = True Workbooks created by this flag set to true are different from regular Workbooks as you can look below.将此标志设置为 true 创建的工作簿与常规工作簿不同,如下所示。

在此处输入图像描述

Functions like insert_cols & insert_rows also do not work for such workbooks. insert_cols 和 insert_rows 等函数也不适用于此类工作簿。

Possible solutions might be to not use this flag or use the ways suggested in the official documentation for adding data to the sheet.可能的解决方案可能是不使用此标志或使用官方文档中建议的方式将数据添加到工作表。

For working with workbooks you might also find this article interesting.对于使用工作簿,您可能还会发现这篇文章很有趣。 https://medium.com/aubergine-solutions/working-with-excel-sheets-in-python-using-openpyxl-4f9fd32de87f https://medium.com/aubergine-solutions/working-with-excel-sheets-in-python-using-openpyxl-4f9fd32de87f

You can read more in the official documentation.您可以在官方文档中阅读更多内容。 https://openpyxl.readthedocs.io/en/stable/optimized.html https://openpyxl.readthedocs.io/en/stable/optimized.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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