extrame / xls

Pure Golang xls library
Apache License 2.0
331 stars 210 forks source link

How to write an XLS file #81

Open lixiaoxi-coder opened 3 years ago

lixiaoxi-coder commented 3 years ago

We can use addSheet addRow to create a WorkBook, but how to write the content of a WorkBook to an XLS file?

Shubhankar-Nath commented 3 years ago

How did you solve this? Have you tried using os.create an xls file and then to open it using xls.Open ? That returns a workbook

lixiaoxi-coder commented 3 years ago

How did you solve this? Have you tried using os.create an xls file and then to open it using xls.Open ? That returns a workbook

No, I have to use python's xls package with go-python.

alok87 commented 1 year ago

@lixiaoxi-coder did you do it? https://github.com/extrame/xls/issues/81#issuecomment-957416017 how was the experience? how fast or slow it is?

shuiYe-704265085 commented 1 year ago

This library seems to only support reading xls files, so I used another library to write xls files (although the other library supports writing files, it does not support reading xls files), as shown in the following code


import (
    "fmt"
    "log"

    "github.com/extrame/xls"
    "github.com/tealeg/xlsx"
)

func main() {
    readXLS()
    // writeHandle()
}

func readXLS() {
    // 打开 XLS 文件
    xlsFile, err := xls.Open("test.xls", "utf-8")
    if err != nil {
        fmt.Println("无法打开 XLS 文件:", err)
        return
    }

    // 获取第一个工作表
    sheet := xlsFile.GetSheet(0)

    // 遍历每一行
    for i := 0; i <= int(sheet.MaxRow); i++ {
        row := sheet.Row(i)

        // 遍历每个单元格
        log.Printf("col:%d~%d\n", row.FirstCol(), row.LastCol())
        for i := row.FirstCol(); i < row.LastCol(); i++ {
            fmt.Printf("%v\t", row.Col(i))
        }

        fmt.Println() // 换行
    }
}

func writeHandle() {
    // 创建一个新的 XLS 文件
    file := xlsx.NewFile()

    // 创建一个工作表
    sheet, err := file.AddSheet("Sheet1")
    if err != nil {
        fmt.Println("无法创建工作表:", err)
        return
    }

    // 添加行和单元格
    row := sheet.AddRow()
    cell := row.AddCell()
    cell.Value = "Hello"

    // 保存文件
    err = file.Save("output.xls")
    if err != nil {
        fmt.Println("保存 XLS 文件失败:", err)
        return
    }

    fmt.Println("XLS 文件保存成功")

}