Go write excel file

1. Download excel Library

go get github.com/xuri/excelize/v2

remarks:
Official documents https://xuri.me/excelize/zh-hans/
Official GitHub https://github.com/qax-os/excelize

2. Use some API functions

① Create Workbook
Use NewFile to create a new Excel workbook. The newly created workbook will contain a worksheet named Sheet1 by default

② Set sheet name
Renames the sheet based on the given old and new sheet names (case sensitive). Sheet names can be up to 31 characters,
This feature only changes the name of the worksheet and does not update the worksheet name in the formula or reference associated with the cell.
Therefore, renaming a worksheet with this function may cause formula errors or reference problems.

③ Concatenate cell names based on rows and columns
name, err := excelize.JoinCellName("A", i+1)

④ Assignment by row
Assign values by row based on the given worksheet name (case sensitive), starting coordinates, and slice type reference.
For example, on the 6th row of the workbook named Sheet1, the B6 cell is used as the starting coordinate to assign values by row:
err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})

⑤ Set formula
Set the formula on the cell according to the given worksheet name (case sensitive) and cell coordinates.
The results of the formula can be calculated when the worksheet is opened by the Office Excel application,
Or calculate the value of the cell through the CalcCellValue function.
If the Excel application does not set the cell formula after opening the workbook, please call UpdateLinkedValue to clear the cell cache after setting the formula.

⑥ Clear cell cache
err = f.UpdateLinkedValue()

⑦ Merge cells
Merge cells according to the given worksheet name (case sensitive) and cell coordinate range. Only the values of the upper left cell will be retained in the merged range, and the values of other cells will be ignored.
For example, merge cells in range D3:E9 on a worksheet named Sheet1:
err := f.MergeCell("Sheet1", "D3", "E9")

⑧ Set cell style
func (f *File) SetCellStyle(sheet, hcell, vcell string, styleID int) error
Sets the value of a cell based on the given worksheet name, cell coordinate range, and style index. The style index can be obtained through the NewStyle function.
Note that diagonalDown and diagonaloup in the same coordinate area need to keep the same color.
SetCellStyle will overwrite the existing style of the cell without overlapping or merging the style with the existing style.

⑩ Set column width
func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) error
Sets the width of one or more columns based on the given worksheet name (case sensitive), column range, and width values. For example, set the width of columns A to H on the worksheet named Sheet1 to 20:
f := excelize.NewFile()
err := f.SetColWidth("Sheet1", "A", "H", 20)

⑪ Create table
Creates a table based on a given worksheet name, cell coordinate range, and conditional format.
Note that the table coordinate area needs to contain at least two rows: a character Title row and a content row.
The characters of each column header row must be unique, and the header row data of the table must be set before calling AddTable function. Coordinate regions of multiple tables cannot have intersection.
Optional parameter table_name is used to set the user-defined table name. The table name in the same worksheet should be unique.
Excel supported table style table_style parameters:
TableStyleLight1 - TableStyleLight21
TableStyleMedium1 - TableStyleMedium28
TableStyleDark1 - TableStyleDark11

⑫ Save as
Use SaveAs to save the Excel document as the specified file.
The specific codes are as follows
package main

import (
    "fmt"
    "github.com/xuri/excelize/v2"
    "strconv"
    "time"
)

func main() {
    //--establish
    //use NewFile newly build Excel Workbook, the newly created workbook will contain a workbook named Sheet1 Worksheet for
    f := excelize.NewFile()

    //--Set sheet name
    //Renames the sheet based on the given old and new sheet names (case sensitive). Sheet names can be up to 31 characters,
    //This feature only changes the name of the worksheet and does not update the worksheet name in the formula or reference associated with the cell.
    //Therefore, renaming a worksheet with this function may cause formula errors or reference problems.
    sheetName := "report card"
    f.SetSheetName("Sheet1", sheetName) //Set the name of the worksheet

    grade := [][]interface{}{
        {"Statistical table of examination results"},
        {"Test name:midsemester", nil, nil, "Wen Zong", nil, nil, "Comprehensive management"},
        {"Serial number", "Student number", "full name", "history", "Geography", "Politics", "biology", "Chemistry", "Physics", "Total score", "average"},
        {1, "1001", "Green Pheasant 1", 11, 22, 33, 44, 55, 66, nil, nil},
        {2, "1002", "Green Pheasant 2", 11, 22, 33, 44, 55, 66, nil, nil},
        {3, "1003", "Green Pheasant 3", 11, 22, 33, 44, 55, 66, nil, nil},
        {4, "1004", "Green Pheasant 4", 11, 22, 33, 44, 55, 66, nil, nil},
        {5, "1005", "Green Pheasant 5", 11, 22, 33, 44, 55, 66, nil, nil},
        {6, "1006", "Green Pheasant 6", 11, 22, 33, 44, 55, 66, nil, nil},
    }
    for i, obj := range grade {
        //--Concatenate cell names based on rows and columns
        name, err := excelize.JoinCellName("A", i+1)
        if err != nil {
            fmt.Println(fmt.Sprintf("Failed to splice cell names,error:%s", err))
            return
        }

        //--Assignment by row
        //Based on the given worksheet name (case sensitive), starting coordinates and slice Type references are assigned by line.
        //For example, in a file named Sheet1 On line 6 of the workbook to B6 Cells as starting coordinates are assigned by row:
        //err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
        err = f.SetSheetRow(sheetName, name, &obj)
        if err != nil {
            fmt.Println(fmt.Sprintf("Failed to write data by row,error:%s", err))
            return
        }
    }

    //--Set formula
    //Set the formula on the cell according to the given worksheet name (case sensitive) and cell coordinates.
    //The results of the formula can be displayed on the worksheet Office Excel Calculated when the application opens,
    //Or through CalcCellValue Function calculates the value of a cell.
    //if Excel After the application opens the workbook, the cell formula is not calculated. Please call it after setting the formula. UpdateLinkedValue Clear cell cache.
    ref := "J4:J9"
    shared := excelize.STCellFormulaTypeShared
    formulaOpts := excelize.FormulaOpts{Type: &shared, Ref: &ref}
    err := f.SetCellFormula(sheetName, "J4", "=SUM(D4:I4)", formulaOpts)
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to set formula,error:%s", err))
        return
    }

    //--Clear cell cache
    err = f.UpdateLinkedValue()
    if err != nil {
        fmt.Println(fmt.Sprintf("Clearing cell cache failed,error:%s", err))
        return
    }

    //After setting the same formula, it is found that it is not applied,So add a formula to each,Ask the boss to explain,Why did I fail to set the same formula in the above code
    //At first, I thought I had changed the name of the worksheet,Later tests are not,Is it WPS Question of?doubt!
    for i := 5; i <= 9; i++ {
        index := strconv.Itoa(i)
        err = f.SetCellFormula(sheetName, "J"+index, fmt.Sprintf("=SUM(D%s:I%s)", index, index), formulaOpts)
        if err != nil {
            fmt.Println(fmt.Sprintf("Failed to set formula,error:%s", err))
            return
        }
    }

    //--merge cell
    //Merge cells according to the given worksheet name (case sensitive) and cell coordinate range. Only the values of the upper left cell will be retained in the merged range, and the values of other cells will be ignored.
    //For example, the merge name is Sheet1 On your worksheet D3:E9 Cells in range:
    //err := f.MergeCell("Sheet1", "D3", "E9")
    //If the given cell coordinate range overlaps with other existing merged cells, the existing merged cells will be deleted.
    err = f.MergeCell(sheetName, "A1", "K1")
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to merge cells,error:%s", err))
        return
    }

    err = f.MergeCell(sheetName, "A2", "C2")
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to merge cells,error:%s", err))
        return
    }

    err = f.MergeCell(sheetName, "D2", "F2")
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to merge cells,error:%s", err))
        return
    }

    err = f.MergeCell(sheetName, "G2", "I2")
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to merge cells,error:%s", err))
        return
    }

    //--Set cell style
    //func (f *File) SetCellStyle(sheet, hcell, vcell string, styleID int) error
    //Sets the value of a cell based on the given worksheet name, cell coordinate range, and style index
    //. The style index can be NewStyle Function get.
    //Note that in the same coordinate area diagonalDown and diagonalUp Color consistency is required.
    //SetCellStyle The existing style of the cell will be overwritten without overlapping or merging the style with the existing style.
    styleCenter, err := f.NewStyle(&excelize.Style{
        Border: nil,
        Fill:   excelize.Fill{},
        Font:   nil,
        Alignment: &excelize.Alignment{
            Horizontal:      "center", //horizontally
            Indent:          0,
            JustifyLastLine: false,
            ReadingOrder:    0,
            RelativeIndent:  0,
            ShrinkToFit:     false,
            TextRotation:    0,
            Vertical:        "", //Vertical center
            WrapText:        false,
        },
        Protection:    nil,
        NumFmt:        0,
        DecimalPlaces: 0,
        CustomNumFmt:  nil,
        Lang:          "",
        NegRed:        false,
    })

    style2, err := f.NewStyle(&excelize.Style{
        Border: nil,
        Fill: excelize.Fill{
            Type:    "pattern", //Solid fill
            Pattern: 1,
            Color:   []string{"DFEBF6"},
            Shading: 0,
        },
        Font: nil,
        Alignment: &excelize.Alignment{
            Horizontal:      "center", //horizontally
            Indent:          0,
            JustifyLastLine: false,
            ReadingOrder:    0,
            RelativeIndent:  0,
            ShrinkToFit:     false,
            TextRotation:    0,
            Vertical:        "", //Vertical center
            WrapText:        false,
        },
        Protection:    nil,
        NumFmt:        0,
        DecimalPlaces: 0,
        CustomNumFmt:  nil,
        Lang:          "",
        NegRed:        false,
    })
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to set style,error:%s", err))
        return
    }
    _ = f.SetCellStyle(sheetName, "A1", "A1", style2)
    _ = f.SetCellStyle(sheetName, "A2", "A2", styleCenter)
    _ = f.SetCellStyle(sheetName, "D2", "D2", styleCenter)
    _ = f.SetCellStyle(sheetName, "G2", "G2", styleCenter)

    //Set column width
    //func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) error
    //Sets the width of one or more columns based on the given worksheet name (case sensitive), column range, and width values. For example, set the name to Sheet1 On the worksheet A reach H The width of the column is 20:
    //f := excelize.NewFile()
    //err := f.SetColWidth("Sheet1", "A", "H", 20)
    _ = f.SetColWidth(sheetName, "D", "D", 7)

    //--Create table
    //Creates a table based on a given worksheet name, cell coordinate range, and conditional format.
    //Note that the table coordinate area needs to contain at least two rows: a character Title row and a content row.
    //The characters of each column header row must be unique and must be called AddTable Function to set the header row data of the table. Coordinate regions of multiple tables cannot have intersection.
    //Optional parameters table_name Used to set custom table names. Table names in the same worksheet should be unique.
    //Excelize Supported table styles table_style Parameters:
    //TableStyleLight1 - TableStyleLight21
    //TableStyleMedium1 - TableStyleMedium28
    //TableStyleDark1 - TableStyleDark11
    err = f.AddTable(sheetName, "A3", "K9", `{"table_name":"form","table_style":"TableStyleLight21"}`)
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to set style,error:%s", err))
        return
    }

    //--Save as
    //use SaveAs preservation Excel The document is the specified file.
    filename := "excel/" + strconv.FormatInt(time.Now().Unix(), 10) + ".xlsx"
    err = f.SaveAs(filename)
    if err != nil {
        fmt.Println(fmt.Sprintf("Failed to save file,error:%s", err))
        return
    }
}

 

Keywords: Go

Added by jpoladsky on Sat, 25 Dec 2021 21:29:24 +0200