xls icon indicating copy to clipboard operation
xls copied to clipboard

How to write an XLS file

Open lixiaoxi-coder opened this issue 4 years ago • 4 comments

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

lixiaoxi-coder avatar Jul 16 '21 02:07 lixiaoxi-coder

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

Shubhankar-Nath avatar Oct 18 '21 18:10 Shubhankar-Nath

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.

lixiaoxi-coder avatar Nov 02 '21 12:11 lixiaoxi-coder

@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?

alok87 avatar Jan 03 '23 08:01 alok87

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 文件保存成功")

}

shuiYe-704265085 avatar Jun 09 '23 01:06 shuiYe-704265085