ASH*_*M.G 5 python excel openpyxl
我需要包含 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
Run Code Online (Sandbox Code Playgroud)
------------------------解决方案2 ----------------------
------------------------解决方案3 ----------------------
也许解决方案 3 是一个更简洁的解决方案!
问题:我希望 max_column 包含“C”列中的数据,它应该返回 10:
简单计数cell.value not Empty
文档访问多个单元格
伪代码
Run Code Online (Sandbox Code Playgroud)for cell in Column('C'): if not cell.value is empty: count += 1
评论:如果我们之间有一个空单元格怎么办?
与列范围同步计算行数,并使用maxRowWithData
变量。这也适用于中间没有空单元格的情况。
伪代码
Run Code Online (Sandbox Code Playgroud)for row index, cell in enumerate Column('C'): if not cell.value is empty: maxRowWithData = row index
注意: 的单元格索引
openpyxl
是从 1 开始的!
文档:enumerate(iterable, start=0)