0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

python xlwings: 最終行のセルを求める

Last updated at Posted at 2021-01-18

pythonのxlwingsで特定の列から要素のある最終行の値を取得・代入する方法です。
途中要素のない行が挟まっても求められます。

Book1.xlsx

行/列 A B C
1 品名
2 りんご 2
3
4 みかん 0
5 いちご 5
fun.py
def lastExcelRow(sheet, col):
       lwr_r_cell = sheet.cells.last_cell      # lower right cell
       lwr_row = lwr_r_cell.row             # row of the lower right cell
       lwr_cell = sheet.range((lwr_row, col))  # change to your specified column

       if lwr_cell.value is None:
           lwr_cell = lwr_cell.end('up')    # go up untill you hit a non-empty cell

       return lwr_cell.row
def lastExcelCell(sheet, col):#colはアルファベットでも数値でもどちらも可
    return sheet.range(( lastExcelRow(sheet, col), col ))
main.py
import xlwings as xw
import fun

bk = xw.Book("Book1.xlsx")
targetSheet = bk.sheets("Sheet1")

# A列の要素のある最終行の値を求める
print( fun.lastExcelCell(targetSheet , "A").value ) # range("A5") -> いちご
# 1列目(=B列)の要素のある最終行を求める
print( fun.lastExcelCell(targetSheet , 2).value ) # range("B5") -> 5

# A列の要素のある最終行の1行下に代入
fun.lastExcelCell(targetSheet, "A").offset(1, 0).value = "めろん" # -> いちごの下行に"めろん"を代入

参考

xlwings.Range 簡易リファレンス
xlwings function to find the last row with data (stackoverrun)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?