yao/excel/excel.go
Max f0da60f467 feat: Migrate Excel plugin to built-in functionality
Move Excel plugin from external plugin to built-in functionality, including:
- Core Excel file operations (open, close, save)
- Sheet manipulation and cell operations
- Row and column iterators
- Process handlers for Excel operations
- Comprehensive test coverage

This change internalizes Excel manipulation capabilities:
- Read/write operations on cells, rows and columns
- Sheet management and styling
- Cell merging and formula handling
- Coordinate conversion utilities
2025-03-21 20:56:35 +08:00

102 lines
1.8 KiB
Go

package excel
import (
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/google/uuid"
"github.com/xuri/excelize/v2"
"github.com/yaoapp/yao/config"
)
// Excel the excel file
type Excel struct {
id string
path string
create int64
*excelize.File
}
// openFiles the open files
var openFiles = sync.Map{}
// Open open the excel file
func Open(path string, writable bool) (string, error) {
excel := &Excel{path: path}
// GET DATA ROOT
root := config.Conf.DataRoot
path, err := filepath.Abs(filepath.Join(root, path))
if err != nil {
return "", err
}
if writable {
// if the file not exists, create it
if _, err := os.Stat(path); os.IsNotExist(err) {
create := excelize.NewFile()
err := create.SaveAs(path)
if err != nil {
return "", err
}
create.Close()
}
excelFile, err := excelize.OpenFile(path)
if err != nil {
return "", err
}
id := uuid.NewString()
excel.File = excelFile
excel.id = id
excel.create = time.Now().Unix()
openFiles.Store(id, excel)
return id, nil
}
file, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("open file %s failed: %w", path, err)
}
excelFile, err := excelize.OpenReader(file)
if err != nil {
return "", err
}
id := uuid.NewString()
excel.File = excelFile
excel.id = id
excel.create = time.Now().Unix()
openFiles.Store(id, excel)
return id, nil
}
// Close close the excel file
func Close(handler string) error {
excel, ok := openFiles.Load(handler)
if !ok {
return fmt.Errorf("file not found")
}
err := excel.(*Excel).Close()
if err != nil {
return err
}
openFiles.Delete(handler)
return nil
}
// Get get the excel file
func Get(handler string) (*Excel, error) {
excel, ok := openFiles.Load(handler)
if !ok {
return nil, fmt.Errorf("%s not found", handler)
}
return excel.(*Excel), nil
}