平常開發中會遇處處理Excel文件的相關操做,這裏推薦一款應用比較普遍的操做Excel的開源工具Excelize。git
Excelize是一個用Go語言編寫的庫,提供了一組容許您寫入和讀取XLSX / XLSM / XLTM文件的功能。支持讀寫由Microsoft Excel™2007和更高版本生成的電子表格文檔。經過高度兼容性支持複雜的組件,並提供了流式API,用於從工做表中生成或讀取包含大量數據的數據。該庫須要Go版本1.10或更高版本。能夠使用go的內置文檔工具查看完整的API文檔,也能夠在go.dev和docs reference上在線查看。github
示例app
package main import ( "fmt" "github.com/360EntSecGroup-Skylar/excelize" ) func main() { f := excelize.NewFile() // Create a new sheet. index := f.NewSheet("Sheet2") // Set value of a cell. f.SetCellValue("Sheet2", "A2", "Hello world.") //設置單元格樣式 style, err := f.NewStyle(`{ "font": { "bold": true, "family": "font-family", "size": 20, "color": "#777777" } }`) if err != nil { fmt.Println(err) } f.SetCellStyle("Sheet1", "B1", "B1", style) f.SetCellValue("Sheet1", "B1", "hello") // Set active sheet of the workbook. f.SetActiveSheet(index) // Save xlsx file by the given path. if err := f.SaveAs("Book1.xlsx"); err != nil { fmt.Println(err) } }
插入圖片到單元格工具
示例:excel
package main import ( "fmt" _ "image/gif" _ "image/jpeg" _ "image/png" "github.com/360EntSecGroup-Skylar/excelize" ) func main() { f, err := excelize.OpenFile("Book1.xlsx") if err != nil { fmt.Println(err) return } // Insert a picture. if err := f.AddPicture("Sheet1", "A2", "image.png", ""); err != nil { fmt.Println(err) } // Insert a picture to worksheet with scaling. if err := f.AddPicture("Sheet1", "D2", "image.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`); err != nil { fmt.Println(err) } // Insert a picture offset in the cell with printing support. if err := f.AddPicture("Sheet1", "H2", "image.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`); err != nil { fmt.Println(err) } // Save the xlsx file with the origin path. if err = f.Save(); err != nil { fmt.Println(err) } }
示例code
package main import ( "fmt" "github.com/360EntSecGroup-Skylar/excelize" ) func main() { f, err := excelize.OpenFile("Book1.xlsx") if err != nil { fmt.Println(err) return } // Get value from cell by given worksheet name and axis. cell, err := f.GetCellValue("Sheet1", "B2") if err != nil { fmt.Println(err) return } fmt.Println(cell) // Get all the rows in the Sheet1. rows, err := f.GetRows("Sheet1") for _, row := range rows { for _, colCell := range row { fmt.Print(colCell, "\t") } fmt.Println() } }
示例圖片
package main import ( "github.com/360EntSecGroup-Skylar/excelize" "log" "net/http" ) func down(w http.ResponseWriter, r *http.Request) { f := excelize.NewFile() // Set value of a cell. f.SetCellValue("Sheet1", "A2", "Hello world.") // Save xlsx file by the given path. //if err := f.SaveAs("Book1.xlsx"); err != nil { // fmt.Println(err) //} w.Header().Set("Content-Type", "application/octet-stream") w.Header().Set("Content-Disposition", "attachment; filename="+"100之內口算題.xlsx") w.Header().Set("Content-Transfer-Encoding", "binary") _ = f.Write(w) } func main() { http.HandleFunc("/", down) // 設置訪問路由 log.Fatal(http.ListenAndServe(":8080", nil)) }