python - 您可以通过将一行中的所有单元格值设置为“无”来使用 openpyxl 删除 Python 中的行吗?
问题描述
我正在使用 openpyxl 尝试从电子表格中删除行。我知道有一个专门用于删除行的功能,但是,我试图在不知道该功能的情况下克服这个问题,我现在想知道为什么我的方法不起作用。
为了简化问题,我建立了一个电子表格,并在其中的一些单元格中填充了字母。在这种情况下,首先print(sheet.max_row)
打印“9”。将所有单元格值设置为 后None
,我希望行数为 0,但是,第二个打印语句再次打印“9”。
是否可以通过将一行中的所有单元格设置为无来减少行数?
import openpyxl
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter, column_index_from_string
spreadsheet = load_workbook(filename = pathToSpreadsheet) #pathToSpreadsheet represents the absolute path I had to the spreadsheet that I created.
sheet = spreadsheet.active
print(sheet.max_row) # Printed "9".
rowCount = sheet.max_row
columnCount = sheet.max_column
finalBoundary = get_column_letter(columnCount) + str(rowCount)
allCellObjects = sheet["A1":finalBoundary]
for rowOfCells in allCellObjects:
for cell in rowOfCells:
cell.value = None
print(sheet.max_row) # Also printed "9".
感谢您的时间和精力!
解决方案
简答NO。但是,您可以使用单元格坐标从工作表访问单元格并将其删除。
for rowOfCells in allCellObjects:
for cell in rowOfCells:
del sheet[cell.coordinate]
print(sheet.max_row)
更详细的答案是 Openpyxl 中的工作表将其存储_cells
为dict
以坐标为键的形式。max_row
属性已定义
@property
def max_row(self):
"""The maximum row index containing data (1-based)
:type: int
"""
max_row = 1
if self._cells:
rows = set(c[0] for c in self._cells)
max_row = max(rows)
return max_row
因此,如果单元格为无,则键/坐标仍将占上风,例如:_cells = {(1,1):None, (1,2):None, (5,4): None}
.
max_row
然后仍然会给我们密钥的最大 y 分量。
推荐阅读
- c# - 从 NodeList 创建 Xml
- sql - 使用 group by 从两列中选择唯一的
- c# - 如何使用 xaml:C# 验证带有 updateSourceTrigger="Explicit" 的文本框中的用户输入?
- ssis - SSIS 项目设置
- mysql - 两个时间框架MYSQL之间的平均时间
- javascript - 我的滑块在 iPad 和 Kindle Fire Linux 模式下无法正常工作
- ms-access-2013 - MS ACCESS:使用按钮形式将所有记录数据从表移动到另一个表
- python - 如何创建一个包含一天中部分时间(晚上、早上、下午、晚上)的新列
- mysql - 在 mysql 条件下选择 IF
- google-cloud-platform - 使用 gcloud 重新验证服务帐户时会发生什么?