Golang Excelize to modify existing workbooks?

Can excelize be used to add worksheets to existing workbook? Has anyone tried it? Please let me know.

1 Like

Hi,
It appears that the excelize module does allow adding sheets to an existing worksheet!!

The code below is modified from the example code in the excelize documentation


package main

import (
	"fmt"

	"github.com/xuri/excelize/v2"
)

func main() {
	f := excelize.NewFile()
	// Create a new sheet.
	//index := f.newsheet("sheet2", "Sheet3", "Sheet4")
	index := f.NewSheet("Sheet3")
	index = f.NewSheet("Sheet2")
	f.SetCellValue("Sheet3", "A2", "Hello world.")
	f.SetCellValue("Sheet2", "A1", "Hello")
	f.SetCellValue("Sheet1", "B2", "First Sheet")
	// Set active sheet of the workbook.
	f.SetActiveSheet(index)
	// Save spreadsheet by the given path.
	if err := f.SaveAs("Book1.xlsx"); err != nil {
		fmt.Println(err)
	}
}

After that, I modified another example code (Badly badly modified…I am sure this is full of errors and lacks checks)


package main

import (
	"fmt"

	"github.com/xuri/excelize/v2"
)

func main() {
	f, err := excelize.OpenFile("Book1.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	index := f.NewSheet("Sheet6")
	// Set value of a cell.
	f.SetCellValue("Sheet6", "A1", "ANOTHER SHEET IS ADDED!!!")
	f.SetCellValue("Sheet6", "A2", "ANOTHER SHEET IS ADDED!!!")
	f.SetCellValue("Sheet6", "A3", "ANOTHER SHEET IS ADDED!!!")
	f.SetCellValue("Sheet6", "A4", "ANOTHER SHEET IS ADDED!!!")
	// Set active sheet of the workbook.
	f.SetActiveSheet(index)
	// Save spreadsheet by the given path.
	if err := f.SaveAs("Book1.xlsx"); err != nil {
		fmt.Println(err)
	}
}

And this works!! I was not sure if f, err := excelize.OpenFile("Book1.xlsx") would allow me to add a sheet, but it does!!
This is simply awesome!!

I should have tried before asking questions here!!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.