Find last filled row in excel using Golang

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

Find last filled row in excel using Golang

问题

我正在寻找一种方法来获取Excel中最后一个填充的行,即:

  1. 1. Lorem Ipsum
  2. 2. qui dolorem ipsum
  3. .
  4. .
  5. nth.architecto beatae vitae <- 这是最后一个填充的行,我该如何获取它的行号?

我正在使用xlsx库来实现这个功能。

英文:

I am looking for a way to get the last filled row in excel I.e

  1. 1. Lorem Ipsum
  2. 2. qui dolorem ipsum
  3. .
  4. .
  5. nth.architecto beatae vitae &lt;- this is the last filled row, how do I get its
  6. number?

I am using the xlsx library for this.

答案1

得分: 3

README的示例中可以看到以下代码:

  1. for _, sheet := range xlFile.Sheets {
  2. for _, row := range sheet.Rows {
  3. for _, cell := range row.Cells {
  4. fmt.Printf("%s\n", cell.String())
  5. }
  6. }
  7. }

这里的_实际上是循环的索引,但在这里被忽略了(因此使用了占位符_)。

但是你可以利用这些索引来处理循环中的行部分:

  1. for _, sheet := range xlFile.Sheets {
  2. rmax := 0
  3. for r, row := range sheet.Rows {
  4. for _, cell := range row.Cells {
  5. fmt.Printf("%s\n", cell.String())
  6. // 如果这一行中至少有一个单元格不为空,
  7. // 记录当前行索引
  8. if cell.String() != "" {
  9. rmax = r
  10. }
  11. }
  12. }
  13. fmt.Printf("最后一行:%d\n", rmax)
  14. }
英文:

From the example of the README

  1. for _, sheet := range xlFile.Sheets {
  2. for _, row := range sheet.Rows {
  3. for _, cell := range row.Cells {
  4. fmt.Printf(&quot;%s\n&quot;, cell.String())
  5. }
  6. }
  7. }

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:

  1. for _, sheet := range xlFile.Sheets {
  2. rmax := 0
  3. for r, row := range sheet.Rows {
  4. for _, cell := range row.Cells {
  5. fmt.Printf(&quot;%s\n&quot;, cell.String())
  6. // If at least one cell in this row is not empty,
  7. // memorize current row index
  8. if cell.String() != &quot;&quot; {
  9. rmax = r
  10. }
  11. }
  12. }
  13. fmt.Printf(&quot;Last line: %d\n&quot;, rmax)
  14. }

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:

确定