码迷,mamicode.com
首页 > 其他好文 > 详细

基于 Golang 的 xls 读取类库:xls

时间:2015-10-23 18:40:07      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

Golang 编写的 xls 读取类库,能够实现 xls 表格的读取功能

func (w *WorkBook) ReadAllCells() (res [][]string) {
    for _, sheet := range w.Sheets {
        w.PrepareSheet(sheet)
        if sheet.MaxRow != 0 {
            temp := make([][]string, sheet.MaxRow+1)
            for k, row := range sheet.Rows {
                data := make([]string, 0)
                if len(row.Cols) > 0 {
                    for _, col := range row.Cols {
                        if uint16(len(data)) <= col.LastCol() {
                            data = append(data, make([]string, col.LastCol()-uint16(len(data))+1)...)
                        }
                        str := col.String(w)
                        for i := uint16(0); i < col.LastCol()-col.FirstCol()+1; i++ {
                            data[col.FirstCol()+i] = str[i]
                        }
                    }
                    temp[k] = data
                }
            }
            res = append(res, temp...)
        }
    }
    return
}

 

读示例:

package main
 
import (
    "fmt"
    "github.com/tealeg/xlsx"
)
 
func main() {
    excelFileName := "/home/tealeg/foo.xlsx"
    xlFile, err := xlsx.OpenFile(excelFileName)
    if err != nil {
        ...
    }
    for _, sheet := range xlFile.Sheets {
        for _, row := range sheet.Rows {
            for _, cell := range row.Cells {
                fmt.Printf("%s\n", cell.String())
            }
        }
    }
}

 写示例:

package main
 
import (
    "fmt"
    "github.com/tealeg/xlsx"
)
 
func main() {
    var file *xlsx.File
    var sheet *xlsx.Sheet
    var row *xlsx.Row
    var cell *xlsx.Cell
    var err error
 
    file = xlsx.NewFile()
    sheet = file.AddSheet("Sheet1")
    row = sheet.AddRow()
    cell = row.AddCell()
    cell.Value = "I am a cell!"
    err = file.Save("MyXLSXFile.xlsx")
    if err != nil {
        fmt.Printf(err.Error())
    }
}

 

基于 Golang 的 xls 读取类库:xls

标签:

原文地址:http://www.cnblogs.com/zhuiluoyu/p/4905195.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!