Skip to content

Instantly share code, notes, and snippets.

@caiomoura1994
Last active June 14, 2023 01:59
Show Gist options
  • Save caiomoura1994/c9c63bfb4670cd3f9865874a5f1a167f to your computer and use it in GitHub Desktop.
Save caiomoura1994/c9c63bfb4670cd3f9865874a5f1a167f to your computer and use it in GitHub Desktop.
add sheets with chain
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/xuri/excelize/v2"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Loan struct {
ID uint
Name string
Company string
}
func main() {
dsn := os.Getenv("POSTGRES_CONNECTION_STRING")
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database: ", err)
}
defer db.Close()
var loans []Loan
if err := db.Find(&loans).Error; err != nil {
log.Fatal("Failed to query database: ", err)
}
if err := generateReport(loans); err != nil {
log.Fatal("Failed to generate report: ", err)
}
}
func generateReport(loans []Loan) error {
file := excelize.NewFile()
sheetName := "Sheet1"
file.SetCellValue(sheetName, "A1", "ID")
file.SetCellValue(sheetName, "B1", "Name")
file.SetCellValue(sheetName, "C1", "Company")
loanCh := make(chan Loan)
for i := 0; i < len(loans); i++ {
go func(l Loan) {
addLoanToSheet(file, sheetName, l)
loanCh <- l
}(loans[i])
}
for i := 0; i < len(loans); i++ {
<-loanCh
}
if err := file.SaveAs("report.xlsx"); err != nil {
return err
}
return nil
}
func addLoanToSheet(file *excelize.File, sheetName string, loan Loan) {
row := len(file.GetRows(sheetName)) + 1
cell := fmt.Sprintf("A%d", row)
file.SetCellValue(sheetName, cell, loan.ID)
cell = fmt.Sprintf("B%d", row)
file.SetCellValue(sheetName, cell, loan.Name)
cell = fmt.Sprintf("C%d", row)
file.SetCellValue(sheetName, cell, loan.Company)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment