Resolve #348, support delete Data Validation

This commit is contained in:
xuri 2020-03-13 00:48:16 +08:00
parent 9e2318cefa
commit 6ab5b991e4
No known key found for this signature in database
GPG Key ID: BA5E5BB1C948EDF7
3 changed files with 46 additions and 5 deletions

View File

@ -228,14 +228,38 @@ func convDataValidationOperatior(o DataValidationOperator) string {
// err = f.AddDataValidation("Sheet1", dvRange)
//
func (f *File) AddDataValidation(sheet string, dv *DataValidation) error {
xlsx, err := f.workSheetReader(sheet)
ws, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if nil == xlsx.DataValidations {
xlsx.DataValidations = new(xlsxDataValidations)
if nil == ws.DataValidations {
ws.DataValidations = new(xlsxDataValidations)
}
xlsx.DataValidations.DataValidation = append(xlsx.DataValidations.DataValidation, dv)
xlsx.DataValidations.Count = len(xlsx.DataValidations.DataValidation)
ws.DataValidations.DataValidation = append(ws.DataValidations.DataValidation, dv)
ws.DataValidations.Count = len(ws.DataValidations.DataValidation)
return err
}
// DeleteDataValidation delete data validation by given worksheet name and
// reference sequence.
func (f *File) DeleteDataValidation(sheet, sqref string) error {
ws, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if ws.DataValidations == nil {
return nil
}
dv := ws.DataValidations
for i := 0; i < len(dv.DataValidation); i++ {
if dv.DataValidation[i].Sqref == sqref {
dv.DataValidation = append(dv.DataValidation[:i], dv.DataValidation[i+1:]...)
i--
}
}
dv.Count = len(dv.DataValidation)
if dv.Count == 0 {
ws.DataValidations = nil
}
return nil
}

View File

@ -85,3 +85,20 @@ func TestDataValidationError(t *testing.T) {
f = NewFile()
assert.EqualError(t, f.AddDataValidation("SheetN", nil), "sheet SheetN is not exist")
}
func TestDeleteDataValidation(t *testing.T) {
f := NewFile()
assert.NoError(t, f.DeleteDataValidation("Sheet1", "A1:B2"))
dvRange := NewDataValidation(true)
dvRange.Sqref = "A1:B2"
assert.NoError(t, dvRange.SetRange(10, 20, DataValidationTypeWhole, DataValidationOperatorBetween))
dvRange.SetInput("input title", "input body")
assert.NoError(t, f.AddDataValidation("Sheet1", dvRange))
assert.NoError(t, f.DeleteDataValidation("Sheet1", "A1:B2"))
assert.NoError(t, f.SaveAs(filepath.Join("test", "TestDeleteDataValidation.xlsx")))
// Test delete data validation on no exists worksheet.
assert.EqualError(t, f.DeleteDataValidation("SheetN", "A1:B2"), "sheet SheetN is not exist")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 186 KiB

After

Width:  |  Height:  |  Size: 134 KiB