excelize icon indicating copy to clipboard operation
excelize copied to clipboard

Add function that returns populated cells in sheet

Open henryx opened this issue 5 years ago • 4 comments

For a better management (e.g. for clearing data in sheet), is useful to add a function that returns all populated cells. For example, if I have an Excel file that I have inserted data in A1 and B4:

f, _ := excelize.OpenFile("file.xlsx")
cells := f.GetPopulatedCells("Sheet1") // cells can be a []string that contains "A1", "B4"

henryx avatar Oct 21 '19 09:10 henryx

This seems to work with the few test cases I tried. I added this to cell.go, not sure where it would be most appropriate.

// GetPopulatedCells provides a function to get the populated cells by given
// worksheet name. It will return the axes of populated cells
func (f *File) GetPopulatedCells(sheet string) ([]string, error) {
	rows, err := f.GetRows(sheet)
	if err != nil {
		fmt.Println(err)
		return []string{""}, nil
	}

	populatedCells := make([]string, 0)

	for rowIndex, row := range rows {
		for colIndex, colCell := range row {
			if colCell != "" {
				cellName, err := CoordinatesToCellName(colIndex+1, rowIndex+1)
				if err != nil {
					fmt.Println(err)
					return []string{""}, nil
				}
				populatedCells = append(populatedCells, cellName)
			}
		}
	}

	return populatedCells, nil
}

drewhbestbuddy avatar Oct 30 '19 12:10 drewhbestbuddy

I've executed a little test. It works. For me it's ok

henryx avatar Nov 05 '19 09:11 henryx

You might want to actually return the errors to be handled instead of printing them and returning an empty list.

mlh758 avatar Nov 05 '19 14:11 mlh758

@henryx Good to hear it is working for you.

@mlh758 Yeah that makes more sense. Maybe something like this instead:

// GetPopulatedCells provides a function to get the populated cells by given
// worksheet name. It will return the axes of populated cells
func (f *File) GetPopulatedCells(sheet string) ([]string, error) {
	rows, err := f.GetRows(sheet)
	if err != nil {
		return nil, err
	}

	populatedCells := make([]string, 0)

	for rowIndex, row := range rows {
		for colIndex, colCell := range row {
			if colCell != "" {
				cellName, err := CoordinatesToCellName(colIndex+1, rowIndex+1)
				if err != nil {
					return nil, err
				}
				populatedCells = append(populatedCells, cellName)
			}
		}
	}

	return populatedCells, nil
}

drewhbestbuddy avatar Nov 07 '19 13:11 drewhbestbuddy