1 Commits
v0.1 ... v0.1.1

Author SHA1 Message Date
f2446daff1 add autowidth 2023-02-11 17:15:31 +11:00

View File

@@ -6,6 +6,7 @@ import (
"fmt"
"log"
"os"
"unicode/utf8"
"github.com/iancoleman/orderedmap"
"github.com/xuri/excelize/v2"
@@ -26,6 +27,7 @@ func main() {
var boldTopRow bool
var freezeTopRow bool
var autoFilter bool
var autoWidth bool
// Process command line arguments
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(&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(&autoWidth, "autowidth", true, "Automatically set the column width to fit contents")
flag.Parse()
var xlsx *excelize.File
@@ -225,6 +228,14 @@ func main() {
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
if err := xlsx.SaveAs(outputFilename); err != nil {
log.Fatal(err)
@@ -260,6 +271,31 @@ func fileExists(filename string) bool {
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() {
s := `{
"number": 4,