Find last filled row in excel using Golang

huangapple go评论100阅读模式
英文:

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 &lt;- 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(&quot;%s\n&quot;, 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(&quot;%s\n&quot;, cell.String())
            // If at least one cell in this row is not empty,
            // memorize current row index
            if cell.String() != &quot;&quot; {
                rmax = r
            }
        }
    }
    fmt.Printf(&quot;Last line: %d\n&quot;, rmax)
}

huangapple
  • 本文由 发表于 2015年2月28日 16:13:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/28779596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定