如何在 python 中找到 excel 的第一个数据行和列 xlwings
How to find first data row and column of excel in python xlwings
我想在 python xlwings 中找到 excel 的第一个数据行和列。以下是示例:
或者
我认为最安全的做法是使用 API
属性 并简单地使用 VBA
Range.Find
方法。我们现在可以使用 *
通配符搜索任何内容,以确保找到公式(可以显示 ""
)和值。一个简化的例子:
import xlwings as xw
app = xw.App(visible=False, add_book=False)
wb = app.books.add()
ws = wb.sheets.active
ws['C2'].value = 'check'
row_cell = ws.api.Cells.Find(What="*", After=ws.api.Cells(ws.api.Rows.Count, ws.api.Columns.Count), LookAt=xw.constants.LookAt.xlPart, LookIn=xw.constants.FindLookIn.xlFormulas, SearchOrder=xw.constants.SearchOrder.xlByRows, SearchDirection=xw.constants.SearchDirection.xlNext, MatchCase=False)
column_cell = ws.api.Cells.Find(What="*", After=ws.api.Cells(ws.api.Rows.Count, ws.api.Columns.Count), LookAt=xw.constants.LookAt.xlPart, LookIn=xw.constants.FindLookIn.xlFormulas, SearchOrder=xw.constants.SearchOrder.xlByColumns, SearchDirection=xw.constants.SearchDirection.xlNext, MatchCase=False)
print((row_cell.Row, column_cell.Column))
我们可以使用 SearchDirection.xlNext
并从最后一个 Excel
单元格开始。这是 VBA
中的一种 recommended 方法,可以可靠地找到您最后使用的 row/column,但也可以可靠地找到您的第一个 row/column.
我想在 python xlwings 中找到 excel 的第一个数据行和列。以下是示例:
或者
我认为最安全的做法是使用 API
属性 并简单地使用 VBA
Range.Find
方法。我们现在可以使用 *
通配符搜索任何内容,以确保找到公式(可以显示 ""
)和值。一个简化的例子:
import xlwings as xw
app = xw.App(visible=False, add_book=False)
wb = app.books.add()
ws = wb.sheets.active
ws['C2'].value = 'check'
row_cell = ws.api.Cells.Find(What="*", After=ws.api.Cells(ws.api.Rows.Count, ws.api.Columns.Count), LookAt=xw.constants.LookAt.xlPart, LookIn=xw.constants.FindLookIn.xlFormulas, SearchOrder=xw.constants.SearchOrder.xlByRows, SearchDirection=xw.constants.SearchDirection.xlNext, MatchCase=False)
column_cell = ws.api.Cells.Find(What="*", After=ws.api.Cells(ws.api.Rows.Count, ws.api.Columns.Count), LookAt=xw.constants.LookAt.xlPart, LookIn=xw.constants.FindLookIn.xlFormulas, SearchOrder=xw.constants.SearchOrder.xlByColumns, SearchDirection=xw.constants.SearchDirection.xlNext, MatchCase=False)
print((row_cell.Row, column_cell.Column))
我们可以使用 SearchDirection.xlNext
并从最后一个 Excel
单元格开始。这是 VBA
中的一种 recommended 方法,可以可靠地找到您最后使用的 row/column,但也可以可靠地找到您的第一个 row/column.