Browse Source

added methods ToSliceUnmerged and FileToSliceUnmerged

Nikolay Bystritskiy 8 years ago
parent
commit
8efec5337b
3 changed files with 62 additions and 0 deletions
  1. 48 0
      file.go
  2. 14 0
      file_test.go
  3. BIN
      testdocs/merged_cells.xlsx

+ 48 - 0
file.go

@@ -85,6 +85,18 @@ func FileToSlice(path string) ([][][]string, error) {
 	return f.ToSlice()
 }
 
+// FileToSliceUnmerged is a wrapper around File.ToSliceUnmerged
+// It returns the raw data contained in an Excel XLSX file as three
+// dimensional slice. Merged cell will be unmerged and values of "origins"
+// will be written to "covered" cells
+func FileToSliceUnmerged(path string) ([][][]string, error) {
+	f, err := OpenFile(path)
+	if err != nil {
+		return nil, err
+	}
+	return f.ToSliceUnmerged()
+}
+
 // Save the File to an xlsx file at the provided path.
 func (f *File) Save(path string) (err error) {
 	target, err := os.Create(path)
@@ -333,3 +345,39 @@ func (file *File) ToSlice() (output [][][]string, err error) {
 	}
 	return output, nil
 }
+
+// ToSliceUnmerged returns the raw data contained in the File as three
+// dimensional slice (s. method ToSlice)
+// The "covered" cells become the value of its "original" cell.
+// Example: Table where A1:A2 merged
+// | 01.01.2011 | Bread | 20 |
+// |            | Fish  | 70 |
+// This sheet will be converted to the slice:
+// [  [01.01.2011 Bread 20]
+// 		[01.01.2011 Fish 70] ]
+func (f *File) ToSliceUnmerged() (output [][][]string, err error) {
+	output, err = f.ToSlice()
+	if err != nil {
+		return nil, err
+	}
+
+	for s, sheet := range f.Sheets {
+		for r, row := range sheet.Rows {
+			for c, cell := range row.Cells {
+				if cell.HMerge > 0 {
+					for i := c + 1; i <= c+cell.HMerge; i++ {
+						output[s][r][i] = output[s][r][c]
+					}
+				}
+
+				if cell.VMerge > 0 {
+					for i := r + 1; i <= r+cell.VMerge; i++ {
+						output[s][i][c] = output[s][r][c]
+					}
+				}
+			}
+		}
+	}
+
+	return output, nil
+}

+ 14 - 0
file_test.go

@@ -789,6 +789,20 @@ func fileToSliceCheckOutput(c *C, output [][][]string) {
 	c.Assert(len(output[2]), Equals, 0)
 }
 
+func (s *SliceReaderSuite) TestFileToSliceUnmerged(c *C) {
+	output, err := FileToSliceUnmerged("./testdocs/testfile.xlsx")
+	c.Assert(err, IsNil)
+	fileToSliceCheckOutput(c, output)
+
+	// merged cells
+	output, err = FileToSliceUnmerged("./testdocs/merged_cells.xlsx")
+	c.Assert(err, IsNil)
+	c.Assert(output[0][6][2], Equals, "Happy New Year!")
+	c.Assert(output[0][6][1], Equals, "Happy New Year!")
+	c.Assert(output[0][1][0], Equals, "01.01.2016")
+	c.Assert(output[0][2][0], Equals, "01.01.2016")
+}
+
 func (l *FileSuite) TestReadWorkbookWithTypes(c *C) {
 	var xlsxFile *File
 	var err error

BIN
testdocs/merged_cells.xlsx