Ver Fonte

fix #503 rows next issue

ducquangkstn há 6 anos atrás
pai
commit
866fda2300
2 ficheiros alterados com 23 adições e 3 exclusões
  1. 3 3
      rows.go
  2. 20 0
      rows_test.go

+ 3 - 3
rows.go

@@ -57,7 +57,8 @@ type Rows struct {
 
 // Next will return true if find the next row element.
 func (rows *Rows) Next() bool {
-	return rows.curRow < len(rows.rows)
+	rows.curRow++
+	return rows.curRow <= len(rows.rows)
 }
 
 // Error will return the error when the find next row element
@@ -67,8 +68,7 @@ func (rows *Rows) Error() error {
 
 // Columns return the current row's column values
 func (rows *Rows) Columns() ([]string, error) {
-	curRow := rows.rows[rows.curRow]
-	rows.curRow++
+	curRow := rows.rows[rows.curRow-1]
 
 	columns := make([]string, len(curRow.C))
 	d := rows.f.sharedStringsReader()

+ 20 - 0
rows_test.go

@@ -6,6 +6,7 @@ import (
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 )
 
 func TestRows(t *testing.T) {
@@ -41,6 +42,25 @@ func TestRows(t *testing.T) {
 	}
 }
 
+// test bug https://github.com/360EntSecGroup-Skylar/excelize/issues/502
+func TestRowsIterator(t *testing.T) {
+	const (
+		sheet2         = "Sheet2"
+		expectedNumRow = 11
+	)
+	xlsx, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
+	require.NoError(t, err)
+
+	rows, err := xlsx.Rows(sheet2)
+	require.NoError(t, err)
+	var rowCount int
+	for rows.Next() {
+		rowCount++
+		require.True(t, rowCount <= expectedNumRow, "rowCount is greater than expected")
+	}
+	assert.Equal(t, expectedNumRow, rowCount)
+}
+
 func TestRowsError(t *testing.T) {
 	xlsx, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
 	if !assert.NoError(t, err) {