3 Commits

Author SHA1 Message Date
f2446daff1 add autowidth 2023-02-11 17:15:31 +11:00
6ff19c3c81 remove binary 2023-02-10 15:32:24 +11:00
e4f832ebf2 update 2023-02-10 15:30:46 +11:00
2 changed files with 37 additions and 0 deletions

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
@@ -179,6 +182,7 @@ func main() {
// cell is still a reference to the last cell in the header row
filterRange := "A1:" + cell
fmt.Printf("Setting autofilter to range '%s'\n", filterRange)
// As per docs any filters applied need to be manually processed by us (eg hiding rows with blanks)
err = xlsx.AutoFilter(worksheetName, filterRange, nil)
if err != nil {
fmt.Printf("Error setting autofilter : '%s'\n", err)
@@ -224,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)
@@ -259,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,

Binary file not shown.