Explorar o código

Add RegSearchSheet (#316)

r-uchino %!s(int64=7) %!d(string=hai) anos
pai
achega
9b8baf75ad
Modificáronse 2 ficheiros con 65 adicións e 0 borrados
  1. 13 0
      excelize_test.go
  2. 52 0
      sheet.go

+ 13 - 0
excelize_test.go

@@ -1268,6 +1268,19 @@ func TestSearchSheet(t *testing.T) {
 	t.Log(xlsx.SearchSheet("Sheet1", "A"))
 }
 
+func TestRegSearchSheet(t *testing.T) {
+	xlsx, err := OpenFile("./test/Book1.xlsx")
+	if err != nil {
+		t.Error(err)
+		return
+	}
+	t.Log(xlsx.SearchSheet("Sheet1", "[0-9]"))
+	// Test search in a not exists worksheet.
+	t.Log(xlsx.SearchSheet("Sheet4", ""))
+	// Test search a not exists value.
+	t.Log(xlsx.SearchSheet("Sheet1", ""))
+}
+
 func TestProtectSheet(t *testing.T) {
 	xlsx := NewFile()
 	xlsx.ProtectSheet("Sheet1", nil)

+ 52 - 0
sheet.go

@@ -18,6 +18,7 @@ import (
 	"io/ioutil"
 	"os"
 	"path"
+	"regexp"
 	"strconv"
 	"strings"
 	"unicode/utf8"
@@ -707,6 +708,57 @@ func (f *File) SearchSheet(sheet, value string) []string {
 	return result
 }
 
+// RegSearchSheet provides the ability to retrieve coordinates
+// with the given worksheet name and regular expression
+// For a merged cell, get the coordinates
+// of the upper left corner of the merge area.
+// :example)
+// Search the coordinates where the numerical value in the range of "0-9" of Sheet 1 is described:
+//
+//    xlsx.RegSearchSheet("Sheet1", "[0-9]")
+//
+func (f *File) RegSearchSheet(sheet, value string) []string {
+	xlsx := f.workSheetReader(sheet)
+	result := []string{}
+	name, ok := f.sheetMap[trimSheetName(sheet)]
+	if !ok {
+		return result
+	}
+	if xlsx != nil {
+		output, _ := xml.Marshal(f.Sheet[name])
+		f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
+	}
+	xml.NewDecoder(bytes.NewReader(f.readXML(name)))
+	d := f.sharedStringsReader()
+	var inElement string
+	var r xlsxRow
+	decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
+	for {
+		token, _ := decoder.Token()
+		if token == nil {
+			break
+		}
+		switch startElement := token.(type) {
+		case xml.StartElement:
+			inElement = startElement.Name.Local
+			if inElement == "row" {
+				r = xlsxRow{}
+				_ = decoder.DecodeElement(&r, &startElement)
+				for _, colCell := range r.C {
+					val, _ := colCell.getValueFrom(f, d)
+					regex := regexp.MustCompile(value)
+					if !regex.MatchString(val) {
+						continue
+					}
+					result = append(result, fmt.Sprintf("%s%d", strings.Map(letterOnlyMapF, colCell.R), r.R))
+				}
+			}
+		default:
+		}
+	}
+	return result
+}
+
 // ProtectSheet provides a function to prevent other users from accidentally
 // or deliberately changing, moving, or deleting data in a worksheet. For
 // example, protect Sheet1 with protection settings: