python - Openpyxl:需要在 Excel 中有数据的列中的最大行数
问题描述
我需要包含 Excel 中数据的特定列中的最后一行。在 openpyxl sheet.max_row 或 max_column 中,我们获得了整个工作表中的最大行或列。但我想要的是一个特定的专栏。
我的场景是我必须从数据库中获取一些值并将其附加到 Excel 工作表中特定列的末尾。
在此屏幕截图中,如果我希望 max_column 包含“C”列中的数据,它应该返回 10:
在上图中,如果我想要最后一个包含“C”列数据的单元格,它应该返回 10
------------- 解决方案 1 --------
import pandas as pd
# lt is the dataframe containing the data to be loaded to excel file
for index,i in enumerate(lt):
panda_xl_rd = pd.read_excel('file.xlsx',"sheet_Name") # Panda Dataframe
max = len(panda_xl_rd.iloc[:,(col-1)].dropna())+2 ''' getting the
row_num of
last record in
column
dropna removes
the Nan
values else we
will get
the entire
sheets max
column length .
+2 gets
the next column
right after the
last column to
enter data '''
cellref = sheet.cell(row = max+index, column=col)
cellref.value = i
del panda_xl_rd
----------------------解决方案2 ----------
----------------------解决方案3 ----------
也许解决方案 3 更简洁!
解决方案
“空”是一个相对概念,因此您的代码应该清楚这一点。openpyxl 中的方法保证返回正交结果集:行和列的长度将始终相同。
使用这个我们可以推断出值不是无的单元格列中的最高行。
max_row_for_c = max((c.row for c in ws['C'] if c.value is not None))
推荐阅读
- c# - 带有 78 个单选按钮的调查表单的 C# MySql 插入或更新命令语法
- android - Garmin 使用原生 android/iOS 应用程序通过 BLE 读取设备数据
- c++ - 剥离应用程序不需要的代码的 C++ 库
- python - 如何查看某个类是否存在于列表中
- reactjs - 无法使用 axios 发送身份验证标头
- javascript - 从 textarea 内的文本中删除空格
- javascript - 如何创建自己的 setTimeout 函数?
- c# - 从对象内的其他属性自动分配属性值
- c++ - 如何在 Objective-C 中使用 C++ 单例?
- c# - 列表
具有不同的值类型