英文:
Find last filled row in excel using Golang
问题
我正在寻找一种方法来获取Excel中最后一个填充的行,即:
1. Lorem Ipsum
2. qui dolorem ipsum
.
.
nth.architecto beatae vitae <- 这是最后一个填充的行,我该如何获取它的行号?
我正在使用xlsx库来实现这个功能。
英文:
I am looking for a way to get the last filled row in excel I.e
1. Lorem Ipsum
2. qui dolorem ipsum
.
.
nth.architecto beatae vitae <- this is the last filled row, how do I get its
number?
I am using the xlsx library for this.
答案1
得分: 3
从README的示例中可以看到以下代码:
for _, sheet := range xlFile.Sheets {
for _, row := range sheet.Rows {
for _, cell := range row.Cells {
fmt.Printf("%s\n", cell.String())
}
}
}
这里的_
实际上是循环的索引,但在这里被忽略了(因此使用了占位符_
)。
但是你可以利用这些索引来处理循环中的行部分:
for _, sheet := range xlFile.Sheets {
rmax := 0
for r, row := range sheet.Rows {
for _, cell := range row.Cells {
fmt.Printf("%s\n", cell.String())
// 如果这一行中至少有一个单元格不为空,
// 记录当前行索引
if cell.String() != "" {
rmax = r
}
}
}
fmt.Printf("最后一行:%d\n", rmax)
}
英文:
From the example of the README
for _, sheet := range xlFile.Sheets {
for _, row := range sheet.Rows {
for _, cell := range row.Cells {
fmt.Printf("%s\n", cell.String())
}
}
}
Those _ are actually indexes for the loop, which are here ignored (hence the placeholder '_
')
But nothing prevents you to use those indexes for the row part of those loops:
for _, sheet := range xlFile.Sheets {
rmax := 0
for r, row := range sheet.Rows {
for _, cell := range row.Cells {
fmt.Printf("%s\n", cell.String())
// If at least one cell in this row is not empty,
// memorize current row index
if cell.String() != "" {
rmax = r
}
}
}
fmt.Printf("Last line: %d\n", rmax)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论