excelize
excelize copied to clipboard
Add function that returns populated cells in sheet
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"
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
}
I've executed a little test. It works. For me it's ok
You might want to actually return the errors to be handled instead of printing them and returning an empty list.
@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
}