add autowidth

This commit is contained in:
2023-02-11 17:15:31 +11:00
parent 6ff19c3c81
commit f2446daff1

View File

@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"log" "log"
"os" "os"
"unicode/utf8"
"github.com/iancoleman/orderedmap" "github.com/iancoleman/orderedmap"
"github.com/xuri/excelize/v2" "github.com/xuri/excelize/v2"
@@ -26,6 +27,7 @@ func main() {
var boldTopRow bool var boldTopRow bool
var freezeTopRow bool var freezeTopRow bool
var autoFilter bool var autoFilter bool
var autoWidth bool
// Process command line arguments // Process command line arguments
flag.StringVar(&inputJson, "inputJson", "./input.json", "Full path to input json data file") flag.StringVar(&inputJson, "inputJson", "./input.json", "Full path to input json data file")
@@ -34,6 +36,7 @@ func main() {
flag.BoolVar(&boldTopRow, "bold-toprow", true, "Sets the top row of the worksheet to bold") flag.BoolVar(&boldTopRow, "bold-toprow", true, "Sets the top row of the worksheet to bold")
flag.BoolVar(&freezeTopRow, "freeze-toprow", true, "Freezes the first row of the Excel worksheet") flag.BoolVar(&freezeTopRow, "freeze-toprow", true, "Freezes the first row of the Excel worksheet")
flag.BoolVar(&autoFilter, "autofilter", true, "Sets the auto filter on the first row") flag.BoolVar(&autoFilter, "autofilter", true, "Sets the auto filter on the first row")
flag.BoolVar(&autoWidth, "autowidth", true, "Automatically set the column width to fit contents")
flag.Parse() flag.Parse()
var xlsx *excelize.File var xlsx *excelize.File
@@ -225,6 +228,14 @@ func main() {
row++ row++
} }
// Perform any post processing now that the data exists
if autoWidth {
err = SetColAutoWidth(xlsx, worksheetName)
if err != nil {
fmt.Printf("Error setting auto width : '%s'\n", err)
}
}
// Close off the file // Close off the file
if err := xlsx.SaveAs(outputFilename); err != nil { if err := xlsx.SaveAs(outputFilename); err != nil {
log.Fatal(err) log.Fatal(err)
@@ -260,6 +271,31 @@ func fileExists(filename string) bool {
return !info.IsDir() return !info.IsDir()
} }
// Taken from https://github.com/qax-os/excelize/issues/92#issuecomment-821578446
func SetColAutoWidth(f *excelize.File, sheetName string) error {
// Autofit all columns according to their text content
cols, err := f.GetCols(sheetName)
if err != nil {
return err
}
for idx, col := range cols {
largestWidth := 0
for _, rowCell := range col {
cellWidth := utf8.RuneCountInString(rowCell) + 2 // + 2 for margin
if cellWidth > largestWidth {
largestWidth = cellWidth
}
}
name, err := excelize.ColumnNumberToName(idx + 1)
if err != nil {
return err
}
f.SetColWidth(sheetName, name, name, float64(largestWidth))
}
// No errors at this point
return nil
}
func TestUnmarshalJSON() { func TestUnmarshalJSON() {
s := `{ s := `{
"number": 4, "number": 4,