Przeglądaj źródła

Merge pull request #379 from rentiansheng/maybeAddcol

fixed sheet.Col index out of range fixed #378
Ryan Hollis 7 lat temu
rodzic
commit
5bf5d38c1f
2 zmienionych plików z 20 dodań i 19 usunięć
  1. 19 17
      sheet.go
  2. 1 2
      sheet_test.go

+ 19 - 17
sheet.go

@@ -59,13 +59,20 @@ func (s *Sheet) AddRow() *Row {
 // Make sure we always have as many Cols as we do cells.
 func (s *Sheet) maybeAddCol(cellCount int) {
 	if cellCount > s.MaxCol {
-		col := &Col{
-			style:     NewStyle(),
-			Min:       cellCount,
-			Max:       cellCount,
-			Hidden:    false,
-			Collapsed: false}
-		s.Cols = append(s.Cols, col)
+		loopCnt := cellCount - s.MaxCol
+		currIndex := s.MaxCol + 1
+		for i := 0; i < loopCnt; i++ {
+
+			col := &Col{
+				style:     NewStyle(),
+				Min:       currIndex,
+				Max:       currIndex,
+				Hidden:    false,
+				Collapsed: false}
+			s.Cols = append(s.Cols, col)
+			currIndex++
+		}
+
 		s.MaxCol = cellCount
 	}
 }
@@ -105,17 +112,12 @@ func (s *Sheet) SetColWidth(startcol, endcol int, width float64) error {
 	if startcol > endcol {
 		return fmt.Errorf("Could not set width for range %d-%d: startcol must be less than endcol.", startcol, endcol)
 	}
-	col := &Col{
-		style:     NewStyle(),
-		Min:       startcol + 1,
-		Max:       endcol + 1,
-		Hidden:    false,
-		Collapsed: false,
-		Width:     width}
-	s.Cols = append(s.Cols, col)
-	if endcol+1 > s.MaxCol {
-		s.MaxCol = endcol + 1
+	end := endcol + 1
+	s.maybeAddCol(end)
+	for ; startcol < end; startcol++ {
+		s.Cols[startcol].Width = width
 	}
+
 	return nil
 }
 

+ 1 - 2
sheet_test.go

@@ -232,12 +232,11 @@ func (s *SheetSuite) TestSetColWidth(c *C) {
 	sheet, _ := file.AddSheet("Sheet1")
 	_ = sheet.SetColWidth(0, 0, 10.5)
 	_ = sheet.SetColWidth(1, 5, 11)
-
 	c.Assert(sheet.Cols[0].Width, Equals, 10.5)
 	c.Assert(sheet.Cols[0].Max, Equals, 1)
 	c.Assert(sheet.Cols[0].Min, Equals, 1)
 	c.Assert(sheet.Cols[1].Width, Equals, float64(11))
-	c.Assert(sheet.Cols[1].Max, Equals, 6)
+	c.Assert(sheet.Cols[1].Max, Equals, 2)
 	c.Assert(sheet.Cols[1].Min, Equals, 2)
 }