首页 > 解决方案 > 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 ----------

https://stackoverflow.com/a/52816289/10003981

----------------------解决方案3 ----------

https://stackoverflow.com/a/52817637/10003981

也许解决方案 3 更简洁!

标签: pythonexcelopenpyxl

解决方案


“空”是一个相对概念,因此您的代码应该清楚这一点。openpyxl 中的方法保证返回正交结果集:行和列的长度将始终相同。

使用这个我们可以推断出值不是无的单元格列中的最高行。

max_row_for_c = max((c.row for c in ws['C'] if c.value is not None))

推荐阅读