code refactor
This commit is contained in:
168
cmd/main/main.go
168
cmd/main/main.go
@@ -29,6 +29,7 @@ func main() {
|
|||||||
var freezeTopRow bool
|
var freezeTopRow bool
|
||||||
var autoFilter bool
|
var autoFilter bool
|
||||||
var autoWidth bool
|
var autoWidth bool
|
||||||
|
var overwriteFile 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")
|
||||||
@@ -38,70 +39,38 @@ func main() {
|
|||||||
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.BoolVar(&autoWidth, "autowidth", true, "Automatically set the column width to fit contents")
|
||||||
|
flag.BoolVar(&overwriteFile, "overwrite", false, "Set to true to overwrite existing file rather than modifying in place")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
var xlsx *excelize.File
|
var xlsx *excelize.File
|
||||||
var s []byte
|
var s []byte
|
||||||
|
|
||||||
var sheetIndex int
|
//var sheetIndex int
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
var cell string
|
var cell string
|
||||||
var row, column int
|
var row, column int
|
||||||
|
|
||||||
// TODO - truncate worksheetName to the maximum 31 characters
|
// Truncate worksheetName to the maximum 31 characters
|
||||||
|
worksheetName = TruncateString(worksheetName, 31)
|
||||||
|
|
||||||
// Check if xlsx file exists already, and if it does then open and append data
|
// Check if xlsx file exists already, and if it does then open and append data
|
||||||
if fileExists(outputFilename) {
|
if fileExists(outputFilename) {
|
||||||
fmt.Printf("Output spreadsheet '%s' already exists.\n", outputFilename)
|
if overwriteFile {
|
||||||
xlsx, err = excelize.OpenFile(outputFilename)
|
// Delete existing file
|
||||||
if err != nil {
|
err = os.Remove(outputFilename)
|
||||||
fmt.Println(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Since we have an existing workbook, check if the sheet we want to write to already exists
|
|
||||||
sheetFound := false
|
|
||||||
for index, name := range xlsx.GetSheetMap() {
|
|
||||||
if name == worksheetName {
|
|
||||||
fmt.Printf("Found worksheet '%s' at index '%d'\n", worksheetName, index)
|
|
||||||
sheetFound = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !sheetFound {
|
|
||||||
// Create the sheet
|
|
||||||
fmt.Printf("Creating worksheet '%s'\n", worksheetName)
|
|
||||||
sheetIndex, err = xlsx.NewSheet(worksheetName)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error creating worksheet '%s' : %s\n", worksheetName, err)
|
panic(err)
|
||||||
}
|
}
|
||||||
// Set active worksheet
|
// Create new file
|
||||||
fmt.Printf("Setting active sheet to index %d", sheetIndex)
|
xlsx = createWorkbook(worksheetName, outputFilename)
|
||||||
xlsx.SetActiveSheet(sheetIndex)
|
|
||||||
|
} else {
|
||||||
|
xlsx = modifyWorkbook(worksheetName, outputFilename)
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("Creating output spreadsheet '%s'\n", outputFilename)
|
xlsx = createWorkbook(worksheetName, outputFilename)
|
||||||
// Create the file
|
|
||||||
xlsx = excelize.NewFile()
|
|
||||||
|
|
||||||
// Rename the default Sheet1 to this worksheet name
|
|
||||||
if worksheetName != "Sheet1" {
|
|
||||||
fmt.Printf("Renaming default worksheet to '%s'\n", worksheetName)
|
|
||||||
err = xlsx.SetSheetName("Sheet1", worksheetName)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error setting sheet name to '%s': %s\n", worksheetName, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set the document properties
|
|
||||||
err := xlsx.SetDocProps(&excelize.DocProperties{
|
|
||||||
Creator: "json2excel",
|
|
||||||
Created: time.Now().Format(time.RFC3339),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
fmt.Printf("Error setting document properties: %s\n", err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the json input file
|
// Read the json input file
|
||||||
@@ -138,7 +107,9 @@ func main() {
|
|||||||
// Get the keys for the first element so we know what the column names will be
|
// Get the keys for the first element so we know what the column names will be
|
||||||
columnMap := vslice[0].(orderedmap.OrderedMap)
|
columnMap := vslice[0].(orderedmap.OrderedMap)
|
||||||
columnNames := columnMap.Keys()
|
columnNames := columnMap.Keys()
|
||||||
fmt.Printf("Creating excel workbook with following headings : '%v'\n", columnNames)
|
|
||||||
|
// Run code to add column names to the first row of the workbook
|
||||||
|
createHeadingRow(xlsx, worksheetName, columnNames)
|
||||||
|
|
||||||
// Set the style for the header values
|
// Set the style for the header values
|
||||||
// Just handling bold for now but we can do other styles too as per https://xuri.me/excelize/en/style.html#NewStyle
|
// Just handling bold for now but we can do other styles too as per https://xuri.me/excelize/en/style.html#NewStyle
|
||||||
@@ -152,9 +123,6 @@ func main() {
|
|||||||
fmt.Printf("Error generating header style : '%s'\n", err2)
|
fmt.Printf("Error generating header style : '%s'\n", err2)
|
||||||
}
|
}
|
||||||
|
|
||||||
row = 1
|
|
||||||
column = 1
|
|
||||||
|
|
||||||
// Set the style
|
// Set the style
|
||||||
if boldTopRow {
|
if boldTopRow {
|
||||||
err = xlsx.SetRowStyle(worksheetName, row, row, headerStyle)
|
err = xlsx.SetRowStyle(worksheetName, row, row, headerStyle)
|
||||||
@@ -163,15 +131,6 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add the header row
|
|
||||||
for i := 0; i < len(columnNames); i++ {
|
|
||||||
cell, _ = excelize.CoordinatesToCellName(column, row)
|
|
||||||
fmt.Printf("Setting cell %s to value %s\n", cell, columnNames[i])
|
|
||||||
xlsx.SetCellValue(worksheetName, cell, columnNames[i])
|
|
||||||
//xlsx.SetCellStyle(worksheetName, cell, cell, headerStyle)
|
|
||||||
column++
|
|
||||||
}
|
|
||||||
|
|
||||||
// Freeze top row if requested, see https://xuri.me/excelize/en/utils.html#SetPanes
|
// Freeze top row if requested, see https://xuri.me/excelize/en/utils.html#SetPanes
|
||||||
if freezeTopRow {
|
if freezeTopRow {
|
||||||
err = xlsx.SetPanes(worksheetName, &excelize.Panes{
|
err = xlsx.SetPanes(worksheetName, &excelize.Panes{
|
||||||
@@ -284,10 +243,95 @@ func fileExists(filename string) bool {
|
|||||||
return !info.IsDir()
|
return !info.IsDir()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// From https://dev.to/takakd/go-safe-truncate-string-9h0#comment-1hp14
|
||||||
|
func TruncateString(str string, length int) string {
|
||||||
|
if length <= 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if utf8.RuneCountInString(str) < length {
|
||||||
|
return str
|
||||||
|
}
|
||||||
|
|
||||||
|
return string([]rune(str)[:length])
|
||||||
|
}
|
||||||
|
|
||||||
|
func createWorkbook(worksheetName string, outputFilename string) *excelize.File {
|
||||||
|
fmt.Printf("Creating output spreadsheet '%s'\n", outputFilename)
|
||||||
|
var err error
|
||||||
|
// Create the file
|
||||||
|
xlsx := excelize.NewFile()
|
||||||
|
|
||||||
|
// Rename the default Sheet1 to this worksheet name
|
||||||
|
if worksheetName != "Sheet1" {
|
||||||
|
fmt.Printf("Renaming default worksheet to '%s'\n", worksheetName)
|
||||||
|
err = xlsx.SetSheetName("Sheet1", worksheetName)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error setting sheet name to '%s': %s\n", worksheetName, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the document properties
|
||||||
|
err = xlsx.SetDocProps(&excelize.DocProperties{
|
||||||
|
Creator: "json2excel",
|
||||||
|
Created: time.Now().Format(time.RFC3339),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error setting document properties: %s\n", err)
|
||||||
|
}
|
||||||
|
return xlsx
|
||||||
|
}
|
||||||
|
|
||||||
|
func modifyWorkbook(worksheetName string, outputFilename string) *excelize.File {
|
||||||
|
fmt.Printf("Output spreadsheet '%s' already exists.\n", outputFilename)
|
||||||
|
xlsx, err := excelize.OpenFile(outputFilename)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Since we have an existing workbook, check if the sheet we want to write to already exists
|
||||||
|
sheetFound := false
|
||||||
|
for index, name := range xlsx.GetSheetMap() {
|
||||||
|
if name == worksheetName {
|
||||||
|
fmt.Printf("Found worksheet '%s' at index '%d'\n", worksheetName, index)
|
||||||
|
sheetFound = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !sheetFound {
|
||||||
|
// Create the sheet
|
||||||
|
fmt.Printf("Creating worksheet '%s'\n", worksheetName)
|
||||||
|
sheetIndex, err := xlsx.NewSheet(worksheetName)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error creating worksheet '%s' : %s\n", worksheetName, err)
|
||||||
|
}
|
||||||
|
// Set active worksheet
|
||||||
|
fmt.Printf("Setting active sheet to index %d", sheetIndex)
|
||||||
|
xlsx.SetActiveSheet(sheetIndex)
|
||||||
|
}
|
||||||
|
return xlsx
|
||||||
|
}
|
||||||
|
|
||||||
|
func createHeadingRow(xlsx *excelize.File, worksheetName string, columnNames []string) {
|
||||||
|
fmt.Printf("Creating excel workbook with following headings : '%v'\n", columnNames)
|
||||||
|
var cell string
|
||||||
|
row := 1
|
||||||
|
column := 1
|
||||||
|
|
||||||
|
// Add the header row
|
||||||
|
for i := 0; i < len(columnNames); i++ {
|
||||||
|
cell, _ = excelize.CoordinatesToCellName(column, row)
|
||||||
|
fmt.Printf("Setting cell %s to value %s\n", cell, columnNames[i])
|
||||||
|
xlsx.SetCellValue(worksheetName, cell, columnNames[i])
|
||||||
|
//xlsx.SetCellStyle(worksheetName, cell, cell, headerStyle)
|
||||||
|
column++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Taken from https://github.com/qax-os/excelize/issues/92#issuecomment-821578446
|
// Taken from https://github.com/qax-os/excelize/issues/92#issuecomment-821578446
|
||||||
func SetColAutoWidth(f *excelize.File, sheetName string) error {
|
func SetColAutoWidth(xlsx *excelize.File, sheetName string) error {
|
||||||
// Autofit all columns according to their text content
|
// Autofit all columns according to their text content
|
||||||
cols, err := f.GetCols(sheetName)
|
cols, err := xlsx.GetCols(sheetName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -303,7 +347,7 @@ func SetColAutoWidth(f *excelize.File, sheetName string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
f.SetColWidth(sheetName, name, name, float64(largestWidth))
|
xlsx.SetColWidth(sheetName, name, name, float64(largestWidth))
|
||||||
}
|
}
|
||||||
// No errors at this point
|
// No errors at this point
|
||||||
return nil
|
return nil
|
||||||
|
Reference in New Issue
Block a user