This commit is contained in:
Star 2024-11-22 16:33:58 +08:00
commit 18f6d69ff2
7 changed files with 437 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.*
!.gitignore
go.sum
node_modules
package.json

286
Excel.go Normal file
View File

@ -0,0 +1,286 @@
package office
import (
"fmt"
"regexp"
"strconv"
"github.com/ssgo/u"
"github.com/xuri/excelize/v2"
)
// func WriteExcel(excelFile, sheetName string, table [][]string, password *string) error {
// var f *excelize.File
// var err error
// if f, err = excelize.OpenFile(excelFile, excelize.Options{Password: u.String(password)}); err != nil {
// f = excelize.NewFile()
// }
// if sheetName == "" {
// sheetName = "Sheet1"
// }
// if sheetName >= "0" && sheetName <= "9" {
// sheetName = f.GetSheetName(u.Int(sheetName))
// }
// for y, row := range table {
// for x, v := range row {
// _ = f.SetCellStr(sheetName, MakeCellID(x, y), v)
// }
// }
// if err == nil {
// err = f.Save()
// } else {
// err = f.SaveAs(excelFile, excelize.Options{Password: u.String(password)})
// }
// return err
// }
type Excel struct {
filename string
password string
excel *excelize.File
}
func OpenExcel(filename string, password *string) (*Excel, error) {
xls := &Excel{
filename: filename,
password: u.String(password),
}
var err error
if u.FileExists(filename) {
if xls.excel, err = excelize.OpenFile(filename, excelize.Options{Password: xls.password}); err != nil {
xls.excel = excelize.NewFile()
}
} else {
xls.excel = excelize.NewFile()
}
return xls, err
}
func (xls *Excel) Save(filename, password *string) error {
if filename != nil {
xls.filename = *filename
}
if password != nil {
xls.password = *password
}
return xls.excel.SaveAs(xls.filename, excelize.Options{Password: xls.password})
}
var isIntMatcher = regexp.MustCompile(`^\d{1,8}$`)
var isFloatMatcher = regexp.MustCompile(`^[\d.]{1,8}$`)
func (xls *Excel) Set(sheetName string, table [][]any, start, end *string) error {
if sheetName == "" {
sheetName = "Sheet1"
}
if isIntMatcher.MatchString(sheetName) {
sheetName = xls.excel.GetSheetName(u.Int(sheetName))
} else {
if idx, err := xls.excel.GetSheetIndex(sheetName); err != nil || idx == -1 {
if _, err = xls.excel.NewSheet(sheetName); err != nil {
return err
}
} else {
return err
}
}
startX, startY := ParseCellID(u.String(start))
endX, endY := ParseCellID(u.String(end))
for y, row := range table {
if endY > 0 && startY+y > endY {
break
}
for x, v := range row {
if endX > 0 && startX+x > endX {
break
}
// fmt.Println(startX+x, startY+y, MakeCellID(startX+x, startY+y), reflect.TypeOf(v).String(), v)
if err := xls.excel.SetCellValue(sheetName, MakeCellID(startX+x, startY+y), v); err != nil {
return err
}
// fmt.Println(xls.excel.GetCellType(sheetName, MakeCellID(startX+x, startY+y)))
}
}
return nil
}
func (xls *Excel) Sheets() []string {
return xls.excel.GetSheetList()
}
func (xls *Excel) Get(sheetName string, start, end *string) ([][]any, error) {
if sheetName >= "0" && sheetName <= "9" {
sheetName = xls.excel.GetSheetName(u.Int(sheetName))
}
rows, err := xls.excel.GetRows(sheetName)
if err != nil {
return nil, err
}
startX, startY := ParseCellID(u.String(start))
endX, endY := ParseCellID(u.String(end))
result := make([][]any, 0)
for y, row := range rows {
if startY > 0 && y < startY {
continue
}
if endY > 0 && y > endY {
break
}
// result[y-startY] = make([]any, len(row)-startX)
rowData := make([]any, 0)
for x, v := range row {
if startX > 0 && x < startX {
continue
}
if endX > 0 && x > endX {
break
}
cellType, err := xls.excel.GetCellType(sheetName, MakeCellID(x, y))
if err != nil {
return nil, err
}
switch cellType {
case excelize.CellTypeInlineString, excelize.CellTypeSharedString:
rowData = append(rowData, v)
case excelize.CellTypeFormula:
// TODO 获得公式结果
// formula, err := xls.excel.GetCellFormula(sheetName, MakeCellID(j, i))
rowData = append(rowData, v)
case excelize.CellTypeNumber:
if isFloatMatcher.MatchString(v) {
rowData = append(rowData, u.Float64(v))
} else {
rowData = append(rowData, u.Int64(v))
}
case excelize.CellTypeBool:
rowData = append(rowData, u.Bool(v))
case excelize.CellTypeDate:
// TODO 获得日期结果
rowData = append(rowData, v)
case excelize.CellTypeUnset:
if isFloatMatcher.MatchString(v) {
rowData = append(rowData, u.Float64(v))
} else if isIntMatcher.MatchString(v) {
rowData = append(rowData, u.Int64(v))
} else {
rowData = append(rowData, v)
}
case excelize.CellTypeError:
rowData = append(rowData, v)
default:
rowData = append(rowData, v)
}
}
result = append(result, rowData)
}
return result, nil
}
func (xls *Excel) SetData(sheetName string, data []map[string]any, start, end *string) error {
table, err := xls.Get(sheetName, start, end)
if err != nil {
return err
}
fieldIndex := map[string]int{}
fieldNum := 0
if len(table) > 0 {
fieldNum = len(table[0])
for i, v := range table[0] {
fieldIndex[u.String(v)] = i
}
}
for i, item := range data {
if len(table) <= i+1 {
table = append(table, []any{})
}
for k, v := range item {
idx, idxOk := fieldIndex[k]
if !idxOk {
idx = fieldNum
fieldIndex[k] = idx
fieldNum++
for len(table[0]) < idx+1 {
table[0] = append(table[0], "")
}
table[0][idx] = k
}
for len(table[i+1]) < idx+1 {
table[i+1] = append(table[i+1], "")
}
table[i+1][idx] = v
}
}
return xls.Set(sheetName, table, start, end)
}
func (xls *Excel) GetData(sheetName string, start, end *string) ([]map[string]any, error) {
rows, err := xls.Get(sheetName, start, end)
if err != nil {
return nil, err
}
fields := []string{}
if len(rows) > 0 {
for _, v := range rows[0] {
v1 := u.String(v)
if v1 == "" {
v1 = MakeCellID(len(fields), 0)
}
fields = append(fields, v1)
}
}
data := make([]map[string]any, 0)
for i := 1; i < len(rows); i++ {
row := map[string]any{}
for j := 0; j < len(fields); j++ {
if j < len(rows[i]) {
row[fields[j]] = rows[i][j]
} else {
row[fields[j]] = ""
}
}
data = append(data, row)
}
return data, nil
}
func MakeCellID(col, row int) string {
colName := ""
for col >= 0 {
i := col % 26
colName = string(rune(i+65)) + colName
col = col/26 - 1
}
return fmt.Sprint(colName, row+1)
}
func ParseCellID(cell string) (col, row int) {
row = 0
col = 0
for i, c := range cell {
if c >= 'A' && c <= 'Z' {
col = col*26 + int(c-'A'+1)
} else if c >= 'a' && c <= 'z' {
col = col*26 + int(c-'a'+1)
} else {
row, _ = strconv.Atoi(cell[i:])
break
}
}
col--
row--
if col < 0 {
col = 0
}
if row < 0 {
row = 0
}
return col, row
}

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 apigo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

57
excel_test.js Normal file
View File

@ -0,0 +1,57 @@
import office from 'apigo.cc/gojs/office'
import co from 'apigo.cc/gojs/console'
import file from 'apigo.cc/gojs/file'
// 测试 makeCellID
for (let x = 0; x < 1000; x++) {
for (let y = 0; y < 100; y++) {
let cellID = office.makeCellID(x, y)
let [x1, y1] = office.parseCellID(cellID)
if (x1 !== x || y1 !== y) {
co.error('failed', x, y, cellID, x1, y1)
return 'test parseCellID failed'
}
}
}
let x = office.openExcel('a.xlsx', '123456')
x.set(0, [['A', 'B', 'C'], ['1', '2', '3'], [1, 2, 3], [1, 2, 3]])
let d = x.get(0, 'A2')
if (d[0][1] !== '2') {
co.error('test get failed', d)
return 'test get failed'
}
if (d[1][1] !== 2) {
co.error('test get failed', d)
return 'test get failed'
}
x.setData(0, [{ '1': 4, '2': 5, '3': 6 }, { '1': 'A', '2': 'B', '3': 'C' }], 'A2', 'B3')
x.save()
try {
office.openExcel('a.xlsx', '12345')
return 'test openExcel with bad password failed'
} catch {
}
let x1 = office.openExcel('a.xlsx', '123456')
d = x1.getData(0, 'A2', 'C4')
if (d[0]['1'] !== 4) {
co.error('test getData failed', d)
return 'test getData failed'
}
if (d[0]['3'] !== 3) {
co.error('test getData failed', d)
return 'test getData failed'
}
if (d[1]['2'] !== 2) {
co.error('test getData failed', d)
return 'test getData failed'
}
file.remove('a.xlsx')
return true

32
go.mod Normal file
View File

@ -0,0 +1,32 @@
module apigo.cc/gojs/office
go 1.18
require (
apigo.cc/gojs v0.0.6
apigo.cc/gojs/console v0.0.2
apigo.cc/gojs/file v0.0.2
github.com/ssgo/u v1.7.11
github.com/xuri/excelize/v2 v2.9.0
)
require (
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.4 // indirect
github.com/ssgo/config v1.7.9 // indirect
github.com/ssgo/log v1.7.7 // indirect
github.com/ssgo/standard v1.7.7 // indirect
github.com/ssgo/tool v0.4.27 // indirect
github.com/xuri/efp v0.0.0-20240408161823-9ad904a10d6d // indirect
github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7 // indirect
golang.org/x/crypto v0.29.0 // indirect
golang.org/x/net v0.31.0 // indirect
golang.org/x/sys v0.27.0 // indirect
golang.org/x/text v0.20.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

18
office.go Normal file
View File

@ -0,0 +1,18 @@
package office
import (
"apigo.cc/gojs"
)
func init() {
obj := map[string]any{
"openExcel": OpenExcel,
"makeCellID": MakeCellID,
"parseCellID": ParseCellID,
}
gojs.Register("apigo.cc/gojs/office", gojs.Module{
Object: gojs.ToMap(obj),
TsCode: gojs.MakeTSCode(obj),
})
}

30
office_test.go Normal file
View File

@ -0,0 +1,30 @@
package office_test
import (
"fmt"
"testing"
"apigo.cc/gojs"
_ "apigo.cc/gojs/console"
_ "apigo.cc/gojs/file"
_ "apigo.cc/gojs/office"
"github.com/ssgo/u"
)
func testJS(name string, t *testing.T) {
r, err := gojs.RunFile(name + "_test.js")
if err != nil {
t.Fatal(u.BRed("test "+name+" error"), err)
} else if r != true {
t.Fatal(u.BRed("test "+name+" failed"), r)
} else {
fmt.Println(u.BGreen("test " + name + " succeess"))
}
}
func TestOffice(t *testing.T) {
gojs.ExportForDev()
// gojs.WatchRun("excel_test.js")
// gojs.WaitAll()
testJS("excel", t)
}