Python Openpyxl:需要Excel中包含数据的列中的最大行数

Python Openpyxl:需要Excel中包含数据的列中的最大行数,python,excel,openpyxl,Python,Excel,Openpyxl,我需要包含Excel中数据的特定列中的最后一行。在openpyxl sheet.max_行或max_列中,获取整个工作表中的最大行或列。但我想要的是一个特定的专栏 我的场景是,我必须从数据库中获取一些值,并将其附加到Excel工作表中特定列的末尾 在这个屏幕截图中,如果我希望max_列包含列“C”中的数据,它应该返回10: 在上图中,如果我希望最后一个单元格包含列“C”的数据,它应该返回10 -------------解决方案1-------------------- import panda

我需要包含Excel中数据的特定列中的最后一行。在openpyxl sheet.max_行或max_列中,获取整个工作表中的最大行或列。但我想要的是一个特定的专栏

我的场景是,我必须从数据库中获取一些值,并将其附加到Excel工作表中特定列的末尾

在这个屏幕截图中,如果我希望max_列包含列“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----------------------

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

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

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

也许解决方案3更简洁

问题:我希望max_列包含列“C”中的数据,它应返回10:

简单计数
单元格。值不为空

文件

伪代码

for cell in Column('C'):
    if not cell.value is empty:
        count += 1
for row index, cell in enumerate Column('C'):
    if not cell.value is empty:
        maxRowWithData = row index


评论:如果中间有一个空单元格怎么办

计算与列范围同步的行数,并使用
maxRowWithData
变量。这也适用于之间的空单元格

伪代码

for cell in Column('C'):
    if not cell.value is empty:
        count += 1
for row index, cell in enumerate Column('C'):
    if not cell.value is empty:
        maxRowWithData = row index
注意:openpyxl的单元格索引是基于1的

文档:

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

使用此函数,我们可以推断单元格列中值不是None的行的最高行

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

我想我刚刚找到了一种利用熊猫的方法:

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

为什么不直接查找列“C”的长度 结果将是相同的输出-->10 因为当u获得列“C”值时,它会将u表示为元组元素 所以只要取元组的长度,即=10

import Openpyxl

file=openpyxl.load_workbook('example.xlsx')

current_sheet=file.get_sheet_by_name('sheet1')  

Column_C=current_sheet['C']   

print ( len(column_C))

data.close()
data.closed()

接受的答案是不正确的,如果两个单元格之间有一个空单元格,并且有值,那么它将失败。以下是正确的方法

import openpyxl as xl
import os
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    Dir_Name = os.path.join(BASE_DIR, 'Your_Project_Folder_Name_Here')
    xl_file_path = os.path.join(Dir_Name, 'Your_Excel_File_Name_Here.xlsx')
    wb_obj = xl.load_workbook(xl_file_path)
    sheet_obj = wb_obj.active
    number_of_rows = sheet_obj.max_row
    last_row_index_with_data = 0
    while True:
        if sheet_obj.cell(number_of_rows, 1).value != None:
            last_row_index_with_data = number_of_rows
            break
        else:
            number_of_rows -= 1

    print( "last row index having values " , last_row_index_with_data)


通过这种方式,我们从页面的底部到顶部进行检查,当我们发现一个单元格的值不是None时,该行的索引就是我们需要的索引。

如果中间有一个空单元格怎么办?通常我们不会有,但只是好奇这对我有好处!!谢谢你的及时回复。将更新问题部分中的两个解决方案!!它正在抛出错误:NameError:名称“empty”不是defined@ChandraShekhar“NameError:name'empty'未定义”:您是否注意到伪代码这个词,表示它不是工作代码。您必须根据自己的需要将其扩展为有效的Python代码。@stovfl谢谢我错过了这个词谢谢您的及时回复!但这只是返回了我的列名:“C”请将您的解释与代码分开,并提供一个完整的代码块,该代码块的格式正确,并具有有效的解决方案。提前谢谢。