### Install go-excel Library Source: https://github.com/szyhf/go-excel/blob/master/README.md This command installs the go-excel library using the Go package manager. It fetches the latest version of the library and makes it available for use in your Go projects. ```shell go get github.com/szyhf/go-excel ``` -------------------------------- ### Read Excel Data Row by Row (Default Usage) Source: https://github.com/szyhf/go-excel/blob/master/README.md Illustrates the default usage pattern of go-excel, involving creating a `Connecter`, opening an xlsx file, and then creating a `Reader` for a specific sheet. Data is processed row by row using a loop and the `Next()` and `Read()` methods, suitable for large files. The `Reader` can be configured to target specific sheets by name, index, or by inferring from a struct type. ```go func defaultUsage(){ conn := excel.NewConnecter() err := conn.Open("./testdata/simple.xlsx") if err != nil { panic(err) } defer conn.Close() // Generate an new reader of a sheet // sheetNamer: if sheetNamer is string, will use sheet as sheet name. // if sheetNamer is int, will i'th sheet in the workbook, be careful the hidden sheet is counted. i ∈ [1,+inf] // if sheetNamer is a object implements `GetXLSXSheetName()string`, the return value will be used. // otherwise, will use sheetNamer as struct and reflect for it's name. // if sheetNamer is a slice, the type of element will be used to infer like before. rd, err := conn.NewReader(stdSheetName) // Assuming stdSheetName is defined elsewhere, e.g., as a string or struct type if err != nil { panic(err) } defer rd.Close() for rd.Next() { var s Standard // Read a row into a struct. err:=rd.Read(&s) if err!=nil{ panic(err) } fmt.Printf("%+v",s) } // Read all is also supported. // var stdList []Standard // err = rd.ReadAll(&stdList) // if err != nil { // panic(err) // return // } // fmt.Printf("%+v",stdList) // map with string key is support, too. // if value is not string // will try to unmarshal to target type // but will skip if unmarshal failed. // var stdSliceList [][]string // err = rd.ReadAll(&stdSliceList) // if err != nil { // panic(err) // return // } // fmt.Printf("%+v",stdSliceList) // var stdMapList []map[string]string // err = rd.ReadAll(&stdMapList) // if err != nil { // panic(err) // return // } // fmt.Printf("%+v",stdMapList) // Using binary instead of file. // xlsxData, err := ioutil.ReadFile(filePath) // if err != nil { // log.Println(err) // return // } // conn := excel.NewConnecter() // err = conn.OpenBinary(xlsxData) } ``` -------------------------------- ### Connecter.Open - Go: Open and read Excel file from filesystem Source: https://context7.com/szyhf/go-excel/llms.txt The Connecter.Open method opens an XLSX file from the filesystem, allowing access to its sheets. It provides methods to retrieve sheet names, create sheet readers, and access title rows. Remember to close the connecter and reader when done. ```Go package main import ( "fmt" "log" excel "github.com/szyhf/go-excel" ) func main() { conn := excel.NewConnecter() err := conn.Open("./data.xlsx") if err != nil { log.Fatalf("Failed to open file: %v", err) } defer conn.Close() sheetNames := conn.GetSheetNames() fmt.Printf("Available sheets: %v\n", sheetNames) // Output: Available sheets: [Sheet1 Sheet2 Users Orders] reader, err := conn.NewReader("Users") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() fmt.Printf("Title row: %v\n", reader.GetTitles()) // Output: Title row: [ID Name Age Email Active] } ``` -------------------------------- ### Connecter.OpenBinary - Go: Open Excel from byte slice Source: https://context7.com/szyhf/go-excel/llms.txt The Connecter.OpenBinary method enables reading Excel files directly from a byte slice, which is useful for handling in-memory data like uploaded files. It allows subsequent operations such as creating readers for specific sheets and reading their content. ```Go package main import ( "fmt" "io/ioutil" "log" excel "github.com/szyhf/go-excel" ) func main() { xlsxData, err := ioutil.ReadFile("./config.xlsx") if err != nil { log.Fatalf("Failed to read file: %v", err) } conn := excel.NewConnecter() err = conn.OpenBinary(xlsxData) if err != nil { log.Fatalf("Failed to open binary: %v", err) } defer conn.Close() reader, err := conn.NewReader(1) // Read first sheet by index if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() var configs []map[string]string err = reader.ReadAll(&configs) if err != nil { log.Fatalf("Failed to read all: %v", err) } fmt.Printf("Loaded %d configuration entries\n", len(configs)) } ``` -------------------------------- ### Programmatic Field Mapping with go-excel Source: https://context7.com/szyhf/go-excel/llms.txt Demonstrates using the FieldConfig interface to define Excel column mappings programmatically within a Go struct. This method is useful for handling complex mapping scenarios or avoiding issues with struct tags. It requires the go-excel library. ```go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) type Invoice struct { InvoiceNumber string ClientName string Amount float64 Items []string PaymentStatus string } func (i *Invoice) GetXLSXFieldConfigs() map[string]excel.FieldConfig { return map[string]excel.FieldConfig{ "InvoiceNumber": { ColumnName: "Invoice #", IsRequired: true, }, "ClientName": { ColumnName: "Client", DefaultValue: "Unknown Client", }, "Amount": { ColumnName: "Total Amount", DefaultValue: "0.00", }, "Items": { ColumnName: "Line Items", Split: ";", }, "PaymentStatus": { ColumnName: "Status", NilValue: "VOID", }, } } func main() { conn := excel.NewConnecter() err := conn.Open("./invoices.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReader("Invoices") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() var invoices []Invoice err = reader.ReadAll(&invoices) if err != nil { log.Fatalf("Failed to read: %v", err) } data, _ := json.MarshalIndent(invoices, "", " ") fmt.Println(string(data)) } ``` -------------------------------- ### Connecter.OpenReader - Go: Open Excel from zip.Reader Source: https://context7.com/szyhf/go-excel/llms.txt The Connecter.OpenReader method allows opening an Excel file using an existing `zip.Reader`. This offers flexibility when dealing with zipped Excel files or custom archive processing, enabling access to sheet information and data. ```Go package main import ( "archive/zip" "fmt" "log" excel "github.com/szyhf/go-excel" ) func main() { zipReader, err := zip.OpenReader("./archive.xlsx") if err != nil { log.Fatalf("Failed to open zip: %v", err) } defer zipReader.Close() conn := excel.NewConnecter() err = conn.OpenReader(&zipReader.Reader) if err != nil { log.Fatalf("Failed to open reader: %v", err) } defer conn.Close() reader, err := conn.NewReader("DataSheet") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() fmt.Printf("Sheet size: %d bytes\n", reader.GetSheetSize()) } ``` -------------------------------- ### Define Excel Configuration Struct in Go Source: https://github.com/szyhf/go-excel/blob/master/README.md Defines the `Config` struct used for configuring how Excel files are read. It includes options for sheet selection, title row identification, skipping rows, and prefix/suffix for sheet names. This configuration is essential for customizing the data import process. ```go type Config struct { // sheet: if sheet is string, will use sheet as sheet name. // if sheet is a object implements `GetXLSXSheetName()string`, the return value will be used. // otherwise, will use sheet as struct and reflect for it's name. // if sheet is a slice, the type of element will be used to infer like before. Sheet interface{} // Use the index row as title, every row before title-row will be ignore, default is 0. TitleRowIndex int // Skip n row after title, default is 0 (not skip), empty row is not counted. Skip int // Auto prefix to sheet name. Prefix string // Auto suffix to sheet name. Suffix string } ``` -------------------------------- ### Map Struct Fields to Excel Columns with go-excel Source: https://context7.com/szyhf/go-excel/llms.txt This Go code demonstrates using struct tags with the go-excel library for field mapping and transformation. It supports custom column names, default values, string splitting, nil handling, encoding (like JSON), and required field validation. Fields can also be explicitly ignored. ```go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) type Order struct { OrderID int `xlsx:"column(ID)"` CustomerName string `xlsx:"column(Customer);req()"` Items []string `xlsx:"column(Items);split(,);req()"` Total float64 `xlsx:"column(TotalAmount);default(0.00)"` Status string `xlsx:"column(Status);nil(DELETED)"` Notes string `xlsx:"column(Notes);default(No notes)"` Internal string `xlsx:"-"` // Ignored field } type CustomJSON struct { Name string Value int } type OrderWithJSON struct { OrderID int `xlsx:"column(ID)"` Metadata *CustomJSON `xlsx:"column(Metadata);encoding(json)"` } func main() { conn := excel.NewConnecter() err := conn.Open("./orders.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReader("Orders") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() var orders []Order err = reader.ReadAll(&orders) if err != nil { log.Fatalf("Failed to read: %v", err) } for _, order := range orders { data, _ := json.Marshal(order) fmt.Println(string(data)) // Output: {"OrderID":1001,"CustomerName":"Acme Corp","Items":["Widget","Gadget"],"Total":149.99,"Status":"SHIPPED","Notes":"Express delivery","Internal":""} } } ``` -------------------------------- ### Implement Custom Unmarshalers with BinaryUnmarshaler in Go Source: https://context7.com/szyhf/go-excel/llms.txt This Go code illustrates how to support custom unmarshaling logic using the `encoding.BinaryUnmarshaler` interface with the go-excel library. It shows how to parse custom date formats and JSON-encoded metadata into Go structs, enabling complex data transformations directly from Excel cells. ```go package main import ( "encoding/json" "fmt" "log" "time" excel "github.com/szyhf/go-excel" ) type CustomDate struct { time.Time } func (cd *CustomDate) UnmarshalBinary(data []byte) error { t, err := time.Parse("2006-01-02", string(data)) if err != nil { return err } cd.Time = t return nil } type Event struct { EventID int `xlsx:"column(ID)"` EventName string `xlsx:"column(Name)"` EventDate *CustomDate `xlsx:"column(Date)"` Attendees int `xlsx:"column(Attendees)"` } type Metadata struct { Tags []string Priority int } func (m *Metadata) UnmarshalBinary(data []byte) error { return json.Unmarshal(data, m) } type Task struct { TaskID int `xlsx:"column(ID)"` Title string `xlsx:"column(Title)"` Meta *Metadata `xlsx:"column(Metadata)"` } func main() { conn := excel.NewConnecter() err := conn.Open("./events.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReader("Events") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() var events []Event err = reader.ReadAll(&events) if err != nil { log.Fatalf("Failed to read: %v", err) } for _, event := range events { fmt.Printf("Event: %s on %s (%d attendees)\n", event.EventName, event.EventDate.Format("Jan 2, 2006"), event.Attendees) } } ``` -------------------------------- ### Go: Read Rows as String Maps with go-excel Source: https://context7.com/szyhf/go-excel/llms.txt Reads rows from an Excel sheet into a slice of maps, where keys are column names and values are cell content as strings. This is useful for handling dynamic data structures or when explicit type information is not required. The entire sheet is read in one go. ```Go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) func main() { conn := excel.NewConnecter() err := conn.Open("./data.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReader("DynamicData") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() var records []map[string]string err = reader.ReadAll(&records) if err != nil { log.Fatalf("Failed to read: %v", err) } for i, record := range records { data, _ := json.Marshal(record) fmt.Printf("Record %d: %s\n", i, string(data)) // Output: Record 0: {"Column1":"Value1","Column2":"Value2","Column3":"Value3"} } } ``` -------------------------------- ### Go: Batch Read Entire Sheet into Slice of Structs with go-excel Source: https://context7.com/szyhf/go-excel/llms.txt Reads all remaining rows from an Excel sheet into a slice of structs in a single operation. This is efficient for processing entire sheets at once. The struct tags are used for column mapping, and default values can be specified. ```Go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) type Employee struct { ID int `xlsx:"column(EmpID)"` FirstName string `xlsx:"column(FirstName)"` LastName string `xlsx:"column(LastName)"` Department string `xlsx:"column(Dept)"` Salary float64 `xlsx:"column(Salary);default(0)"` } func main() { conn := excel.NewConnecter() err := conn.Open("./employees.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReader("Employees") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() var employees []Employee err = reader.ReadAll(&employees) if err != nil { log.Fatalf("Failed to read all: %v", err) } fmt.Printf("Total employees: %d\n", len(employees)) data, _ := json.MarshalIndent(employees, "", " ") fmt.Println(string(data)) } ``` -------------------------------- ### Configure Advanced Excel Reader Behavior in Go Source: https://context7.com/szyhf/go-excel/llms.txt This Go code snippet demonstrates how to configure the go-excel reader for complex Excel file layouts. It allows specifying the title row position, skipping rows, and defining sheet name prefixes/suffixes. It reads data into a slice of 'Report' structs. ```go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) type Report struct { Quarter string `xlsx:"column(Quarter)"` Revenue float64 `xlsx:"column(Revenue);default(0)"` Expenses float64 `xlsx:"column(Expenses);default(0)"` Profit float64 `xlsx:"column(Profit);default(0)"` } func main() { conn := excel.NewConnecter() err := conn.Open("./quarterly_report.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReaderByConfig(&excel.Config{ Sheet: "Financial", TitleRowIndex: 2, // Title row is the 3rd row (0-indexed) Skip: 1, // Skip 1 row after title before data Prefix: "", Suffix: "_2024", }) if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() var reports []Report err = reader.ReadAll(&reports) if err != nil { log.Fatalf("Failed to read: %v", err) } data, _ := json.MarshalIndent(reports, "", " ") fmt.Println(string(data)) } ``` -------------------------------- ### Unmarshal Excel Data into Go Structs (Simple Usage) Source: https://github.com/szyhf/go-excel/blob/master/README.md Demonstrates the basic usage of go-excel to unmarshal data from an xlsx file directly into a slice of Go structs. The library infers column names from struct field names by default, but can be customized using struct tags for explicit mapping, splitting string values, and handling custom unmarshalling. ```go // defined a struct type Standard struct { // use field name as default column name ID int // column means to map the column name Name string `xlsx:"column(NameOf)"` // you can map a column into more than one field NamePtr *string `xlsx:"column(NameOf)"` // omit `column` if only want to map to column name, it's equal to `column(AgeOf)` Age int `xlsx:"AgeOf"` // split means to split the string into slice by the `|` Slice []int `xlsx:"split(|)"` // *Temp implement the `encoding.BinaryUnmarshaler` Temp *Temp `xlsx:"column(UnmarshalString)"` // support default encoding of json TempEncoding *TempEncoding `xlsx:"column(UnmarshalString);encoding(json)"` // use '-' to ignore. Ignored string `xlsx:"-"` } // func (this Standard) GetXLSXSheetName() string { // return "Some other sheet name if need" // } type Temp struct { Foo string } // self define a unmarshal interface to unmarshal string. func (this *Temp) UnmarshalBinary(d []byte) error { return json.Unmarshal(d, this) } func simpleUsage() { // will assume the sheet name as "Standard" from the struct name. var stdList []Standard err := excel.UnmarshalXLSX("./testdata/simple.xlsx", &stdList) if err != nil { panic(err) } } ``` -------------------------------- ### Custom Sheet Name Resolution with go-excel Source: https://context7.com/szyhf/go-excel/llms.txt Illustrates how to use the GetXLSXSheetName() method to specify custom sheet names for reading Excel data. This overrides the default behavior of inferring sheet names from struct names. Requires the go-excel library. ```go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) type MonthlyData struct { Month string `xlsx:"column(Month)"` Sales float64 `xlsx:"column(Sales)"` Targets float64 `xlsx:"column(Target)"` } func (md MonthlyData) GetXLSXSheetName() string { return "2024_Monthly_Summary" } type QuarterlyData struct { Quarter string `xlsx:"column(Q)"` Revenue float64 `xlsx:"column(Rev)"` } func (qd QuarterlyData) GetXLSXSheetName() string { return "Quarterly_2024" } func main() { var monthlyRecords []MonthlyData err := excel.UnmarshalXLSX("./sales_report.xlsx", &monthlyRecords) if err != nil { log.Fatalf("Failed to unmarshal monthly: %v", err) } var quarterlyRecords []QuarterlyData err = excel.UnmarshalXLSX("./sales_report.xlsx", &quarterlyRecords) if err != nil { log.Fatalf("Failed to unmarshal quarterly: %v", err) } fmt.Println("Monthly Data:") monthlyJSON, _ := json.MarshalIndent(monthlyRecords, "", " ") fmt.Println(string(monthlyJSON)) fmt.Println("\nQuarterly Data:") quarterlyJSON, _ := json.MarshalIndent(quarterlyRecords, "", " ") fmt.Println(string(quarterlyJSON)) } ``` -------------------------------- ### Go: Read Rows as String Slices with go-excel Source: https://context7.com/szyhf/go-excel/llms.txt Reads rows from an Excel sheet into string slices, preserving the column order of the data. This method is suitable for CSV-like processing or when column names are not relevant. It iterates through rows one by one using Next() and Read(). ```Go package main import ( "fmt" "log" "strings" excel "github.com/szyhf/go-excel" ) func main() { conn := excel.NewConnecter() err := conn.Open("./report.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReader("RawData") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() titles := reader.GetTitles() fmt.Printf("Columns: %s\n", strings.Join(titles, " | ")) for reader.Next() { var row []string err := reader.Read(&row) if err != nil { log.Printf("Error: %v", err) continue } fmt.Printf("Data: %s\n", strings.Join(row, " | ")) // Output: Data: 1 | John | Engineering | 75000 } } ``` -------------------------------- ### UnmarshalXLSX - Go: Read entire Excel sheet into structs Source: https://context7.com/szyhf/go-excel/llms.txt The UnmarshalXLSX function reads an entire Excel sheet and unmarshals its data into a slice of Go structs. It infers the sheet name from the struct type. Ensure the struct fields are tagged with `xlsx:"column(...)"` for mapping. ```Go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) type User struct { ID int `xlsx:"column(ID)"` Name string `xlsx:"column(Name)"` Age int `xlsx:"column(Age)"` Email string `xlsx:"column(Email)"` Active bool `xlsx:"column(Active)"` } func main() { var users []User err := excel.UnmarshalXLSX("./users.xlsx", &users) if err != nil { log.Fatalf("Failed to unmarshal: %v", err) } data, _ := json.MarshalIndent(users, "", " ") fmt.Println(string(data)) // Output: [{"ID":1,"Name":"Alice","Age":30,"Email":"alice@example.com","Active":true}, ...] } ``` -------------------------------- ### Go: Read Single Row into Struct with go-excel Source: https://context7.com/szyhf/go-excel/llms.txt Reads the current row from an Excel sheet into a Go struct. This method must be called after Next() positions the cursor on a data row. It uses struct tags for mapping Excel columns to struct fields and supports custom delimiters for slice fields. ```Go package main import ( "encoding/json" "fmt" "log" excel "github.com/szyhf/go-excel" ) type Product struct { ID int `xlsx:"column(ProductID)"` Name string `xlsx:"column(ProductName)"` Price float64 `xlsx:"column(Price)"` Categories []string `xlsx:"column(Categories);split(|)"` InStock bool `xlsx:"column(InStock)"` } func main() { conn := excel.NewConnecter() err := conn.Open("./products.xlsx") if err != nil { log.Fatalf("Failed to open: %v", err) } defer conn.Close() reader, err := conn.NewReader("Products") if err != nil { log.Fatalf("Failed to create reader: %v", err) } defer reader.Close() for reader.Next() { var product Product err := reader.Read(&product) if err != nil { log.Printf("Error reading row: %v", err) continue } data, _ := json.Marshal(product) fmt.Println(string(data)) // Output: {"ID":101,"Name":"Widget","Price":19.99,"Categories":["Electronics","Gadgets"],"InStock":true} } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.