Openpyxl:需要具有Excel中数据的列中的最大行数

时间:2018-10-15 09:48:01

标签: python excel openpyxl

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

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

在此屏幕截图中,如果我希望max_column在“ C”列中包含数据,则应返回10:

image

在上图中,如果我想要最后一个包含列“ 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是更简洁的一种!

5 个答案:

答案 0 :(得分:1)

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

使用此方法,我们可以推断出值不为None的单元格列中的最高行。

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

无))

答案 1 :(得分:0)

  

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

简单计数cell.value not Empty
文档Accessing many cells

  

PSEUDOCODE

for cell in Column('C'):
    if not cell.value is empty:
        count += 1

  

评论:如果我们之间有一个空白单元格该怎么办?

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

  

PSEUDOCODE

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

注意openpyxl的单元格索引是基于 1的

文档: enumerate(iterable, start=0)

答案 2 :(得分:0)

如果两个单元格之间有值的空单元格不正确,则接受的答案将不正确,否则将失败,这是正确的方法。

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时,该行的索引就是我们所需要的。

答案 3 :(得分:-1)

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

->

答案 4 :(得分:-1)

只需执行以下操作:

columntuple=sheet['A']

不在其中添加行,则:

print ( len(colummntuple))

这将为您提供col的长度。

对于行长:

rowtuple=sheet[0]

这将为您提供tuple(A1,B1,C1)的第一行:

len(rowtuple)