diff --git a/excelize.go b/excelize.go index 0b530ab..013f357 100644 --- a/excelize.go +++ b/excelize.go @@ -401,3 +401,43 @@ func (f *File) adjustAutoFilterHelper(xlsx *xlsxWorksheet, column, rowIndex, off } } } + +// GetMergeCells provides a function to get all merged cells from a worksheet currently. +func (f *File) GetMergeCells(sheet string) []MergeCell { + mergeCells := []MergeCell{} + + xlsx := f.workSheetReader(sheet) + if xlsx.MergeCells != nil { + for i := 0; i < len(xlsx.MergeCells.Cells); i++ { + ref := xlsx.MergeCells.Cells[i].Ref + axis := strings.Split(ref, ":")[0] + mergeCells = append(mergeCells, []string{ref, f.GetCellValue(sheet, axis)}) + } + } + + return mergeCells +} + +// MergeCell define a merged cell data. +// It consists of the following structure. +// example: []string{"D4:E10", "cell value"} +type MergeCell []string + +// GetCellValue returns merged cell value. +func (m *MergeCell) GetCellValue() string { + return (*m)[1] +} + +// GetStartAxis returns the merge start axis. +// example: "C2" +func (m *MergeCell) GetStartAxis() string { + axis := strings.Split((*m)[0], ":") + return axis[0] +} + +// GetEndAxis returns the merge end axis. +// example: "D4" +func (m *MergeCell) GetEndAxis() string { + axis := strings.Split((*m)[0], ":") + return axis[1] +} diff --git a/excelize_test.go b/excelize_test.go index c9a87d0..f55ac01 100644 --- a/excelize_test.go +++ b/excelize_test.go @@ -351,6 +351,59 @@ func TestMergeCell(t *testing.T) { } } +func TestGetMergeCells(t *testing.T) { + wants := []struct { + value string + start string + end string + }{ + { + value: "A1", + start: "A1", + end: "B1", + }, + { + value: "A2", + start: "A2", + end: "A3", + }, + { + value: "A4", + start: "A4", + end: "B5", + }, + { + value: "A7", + start: "A7", + end: "C10", + }, + } + + xlsx, err := OpenFile("./test/MergeCell.xlsx") + if err != nil { + t.Error(err) + } + + mergeCells := xlsx.GetMergeCells("Sheet1") + if len(mergeCells) != len(wants) { + t.Fatalf("Expected count of merge cells %d, but got %d\n", len(wants), len(mergeCells)) + } + + for i, m := range mergeCells { + if wants[i].value != m.GetCellValue() { + t.Fatalf("Expected merged cell value %s, but got %s\n", wants[i].value, m.GetCellValue()) + } + + if wants[i].start != m.GetStartAxis() { + t.Fatalf("Expected merged cell value %s, but got %s\n", wants[i].start, m.GetStartAxis()) + } + + if wants[i].end != m.GetEndAxis() { + t.Fatalf("Expected merged cell value %s, but got %s\n", wants[i].end, m.GetEndAxis()) + } + } +} + func TestSetCellStyleAlignment(t *testing.T) { xlsx, err := OpenFile("./test/Book2.xlsx") if err != nil { diff --git a/test/MergeCell.xlsx b/test/MergeCell.xlsx new file mode 100644 index 0000000..d4dad18 Binary files /dev/null and b/test/MergeCell.xlsx differ