golang使用xlsx操纵excel浅析



欢迎直接访问我的博客:http://www.yqun.xyz:1313

Introduction

xlsx is a library to simplify reading and writing the XML format used by recent version of Microsoft Excel in Go programs.

Installation

使用go get

go get github.com/tealeg/xlsx

# 需要注意的是,这里安装依赖于GOPATH这个环境变量。

直接git clone手动安装

git clone https://github.com/tealeg/xlsx.git

# 然后把xlsx放到$GOPATH/src/github.com/目录下就ok了

我在使用go gget安装的时候失败了,错误信息如下:

package golang.org/x/xerrors: unrecognized import path “golang.org/x/xerrors” (https fetch: Get https://golang.org/x/xerrors?go-get=1: dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)

原因就是没有golang.org/x/xerrors没有安装

然后我使用go get安装xerrors也失败了,我就直接git手动安装了。

git clone https://github.com/golang/xerrors.git

# 然后将xerrors放到$GOPATH/src/golang.org/x/目录下就ok了。

How to use

xlsx.File

func NewFile(options… FileOption) *File

NewFile creates a new File struct. You may pass it zero, one or many FileOption functions that affect the behaviour of the file.

func OpenBinary(bs []byte, options …FileOption) (*File, error)

OpenBinary() take bytes of an XLSX file and returns a populated xlsx.File struct for it.

func OpenFile(fileName string, options …FileOption) (file *File, err error)

OpenFile will take the name of an XLSX file and returns a populated xlsx.File struct for it. You may pass it zero, one or many FileOption functions that affect the behaviour of the file.

func OpenReaderAt(r io.ReaderAt, size int64, options …FileOption) (*File, error)

OpenReaderAt() take io.ReaderAt of an XLSX file and returns a populated xlsx.File struct for it.

func ReadZip(f *zip.ReadCloser, options …FileOption) (*File, error)

OpenReaderAt() take io.ReaderAt of an XLSX file and returns a populated xlsx.File struct for it.

func ReadZipReader(r *zip.Reader, options …FileOption) (*File, error)

ReadZipReader() can be used to read an XLSX in memory without touching the filesystem.

func (f *File) AddSheet(sheetName string) (*Sheet, error)

AddSheet Add a new Sheet, with the provided name, to a File. The minimum sheet name length is 1 character. If the sheet name length is less an error is thrown. The maximum sheet name length is 31 characters. If the sheet name length is exceeded an error is thrown. These special characters are also not allowed: : \ / ? * [ ]

AddSheet将具有提供的名称的新工作表添加到文件。 工作表名称的最小长度为1个字符。 如果工作表名称长度短,则会引发错误。 工作表名称的最大长度为31个字符。 如果超过工作表名称的长度,则会引发错误。 也不允许使用这些特殊字符::\ /? * []

func (f *File) AddSheetWithCellStore(sheetName string, constructor CellStoreConstructor) (*Sheet, error)

使用用户提供的Cell的构造器

func (f *File) AppendSheet(sheet Sheet, sheetName string) (*Sheet, error)

Appends an existing Sheet, with the provided name, to a File

func (f *File) MarshallParts() (map[string]string, error)

Construct a map of file name to XML content representing the file in terms of the structure of an XLSX file.

根据XLSX文件的结构,构造一个文件名到表示该文件的XML内容的映射。

func (f *File) Save(path string) (err error)

Save the File to an xlsx file at the provided path.

func (f *File) ToSlice() (output [][][]string, err error)

Return the raw data contained in the File as three dimensional slice. The first index represents the sheet number, the second the row number, and the third the cell number.

以三维切片的形式返回文件中包含的原始数据。 第一个索引代表页码,第二个索引代表行号,第三个代表单元格号。

For example:
var mySlice [][][]string
var value string
mySlice = xlsx.FileToSlice("myXLSX.xlsx")
value = mySlice[0][0][0]

Here, value would be set to the raw value of the cell A1 in the first sheet in the XLSX file.

func (f *File) ToSliceUnmerged() (output [][][]string, err error)

ToSliceUnmerged returns the raw data contained in the File as three dimensional slice (s. method ToSlice). A covered cell become the value of its origin cell. Example: table where A1:A2 merged. | 01.01.2011 | Bread | 20 | | | Fish | 70 | This sheet will be converted to the slice: [ [01.01.2011 Bread 20] [01.01.2011 Fish 70] ]

func (f *File) Write(writer io.Writer) (err error)

Write the File to io.Writer as xlsx

FileOption

type FileOption func(f *File)

xlsx.Sheet

Defination

type Sheet struct {
    Name            string
    File            *File
    Cols            *ColStore
    MaxRow          int
    MaxCol          int
    Hidden          bool
    Selected        bool
    SheetViews      []SheetView
    SheetFormat     SheetFormat
    AutoFilter      *AutoFilter
    Relations       []Relation
    DataValidations []*xlsxDataValidation
    // contains filtered or unexported fields
}

Sheet is a high level structure intended to provide user access to the contents of a particular sheet within an XLSX file.

func NewSheet(name string) (*Sheet, error)

NewSheet constructs a Sheet with the default CellStore and returns a pointer to it.

func NewSheetWithCellStore(name string, constructor CellStoreConstructor) (*Sheet, error)

NewSheetWithCellStore constructs a Sheet, backed by a CellStore, for which you must provide the constructor function.

func (s *Sheet) AddDataValidation(dv *xlsxDataValidation)

Add a DataValidation to a range of cells

添加数据验证方式

func (s *Sheet) AddRow() *Row

Add a new Row to a Sheet

func (s *Sheet) AddRowAtIndex(index int) (*Row, error)

Add a new Row to a Sheet at a specific index

func (s *Sheet) Cell(row, col int) (*Cell, error)

Get a Cell by passing it’s cartesian coordinates (zero based) as row and column integer indexes.

Example
cell := sheet.Cell(0,0)

func (s *Sheet) Close()

Remove Sheet’s dependant resources - if you are done with operations on a sheet this should be called to clear down the Sheet’s persistent cache. Typically this happens after you’ve saved your changes.

删除工作表的依赖资源-如果您完成了工作表上的操作,则应调用它来清除工作表的持久性缓存。 通常,这种情况发生在您保存更改之后*。

func (s *Sheet) Col(idx int) *Col

Return the Col that applies to this Column index, or return nil if no such Col exists

返回适用于此列索引的列,如果不存在此列,则返回nil

func (s *Sheet) ForEachRow(rv RowVisitor) error

对sheet的每一行进行rv处理

func (s *Sheet) Row(idx int) (*Row, error)

Make sure we always have as many Rows as we do cells.

func (s *Sheet) SetColParameters(col *Col)

设置列的参数。 参数作为指向您自己构造的Col结构的指针传递。

func (s *Sheet) SetColWidth(min, max int, width float64)

Set the width of a range of columns.

func (s *Sheet) SetOutlineLevel(minCol, maxCol int, outlineLevel uint8)

Set the outline level for a range of columns.

func (s *Sheet) SetType(minCol, maxCol int, cellType CellType)

Set the type for a range of columns.

xlsx.Row

defination

type Row struct {
    Hidden       bool    // Hidden determines whether this Row is hidden or not.
    Sheet        *Sheet  // Sheet is a reference back to the Sheet that this Row is within.
    Height       float64 // Height is the current height of the Row in PostScript Points
    OutlineLevel uint8   // OutlineLevel contains the outline level of this Row.  Used for collapsing.
    // contains filtered or unexported fields
}

Row表示当前工作表中的单个行。

func (r *Row) AddCell() *Cell

AddCell adds a new Cell(单元格) to the Row

func (r *Row) ForEachCell(cvf CellVisitorFunc) error

ForEachCell will call the provided CellVisitorFunc for each currently defined cell in the Row.

ForEachCell将为Row中的每个当前定义的单元格调用提供的CellVisitorFunc。

func (r *Row) GetCell(colIdx int) *Cell

GetCell returns the Cell at a given column index, creating it if it doesn’t exist.

func (r *Row) ReadStruct(ptr interface{}) error

ReadStruct reads a struct from r to ptr. Accepts a ptr to struct. This code expects a tag xlsx:“N”, where N is the index of the cell to be used. Basic types like int,string,float64 and bool are supported

ReadStruct从r到ptr读取一个结构。 接受ptr进行构造。 该代码需要一个标签xlsx:“ N”,其中N是要使用的单元格的索引。 支持int,string,float64和bool等基本类型。

其实就是使用一个结构体对Row的数据进行解析(parse)

Example
//example type
type structTest struct {
    IntVal     int     `xlsx:"0"`
    StringVal  string  `xlsx:"1"`
    FloatVal   float64 `xlsx:"2"`
    IgnoredVal int     `xlsx:"-"`
    BoolVal    bool    `xlsx:"4"`
}
structVal := structTest{
    IntVal:     16,
    StringVal:  "heyheyhey :)!",
    FloatVal:   3.14159216,
    IgnoredVal: 7,
    BoolVal:    true,
}
//create a new xlsx file and write a struct
//in a new row
f := NewFile()
sheet, _ := f.AddSheet("TestRead")
row := sheet.AddRow()
row.WriteStruct(&structVal, -1)

//read the struct from the same row
readStruct := &structTest{}
err := row.ReadStruct(readStruct)
if err != nil {
    panic(err)
}
fmt.Println(readStruct)

func (r *Row) SetHeight(ht float64)

SetHeight sets the height of the Row in PostScript Points

func (r *Row) SetHeightCM(ht float64)

SetHeightCM sets the height of the Row in centimetres, inherently converting it to PostScript points.

SetHeightCM以厘米为单位设置行的高度,固有地将其转换为PostScript点。

func (r *Row) WriteSlice(e interface{}, cols int) int

Writes an array to row r. Accepts a pointer to array type ‘e’, and writes the number of columns to write, ‘cols’. If ‘cols’ is < 0, the entire array will be written if possible. Returns -1 if the ‘e’ doesn’t point to an array, otherwise the number of columns written.

将数组写入r行。 接受一个指向数组类型’e’的指针,并写入要写入的列数’cols’。 如果’cols’<0,则将尽可能写入整个数组。 如果’e’不指向数组,则返回-1,否则返回写入的列数。

func (r *Row) WriteStruct(e interface{}, cols int) int

Writes a struct to row r. Accepts a pointer to struct type ‘e’, and the number of columns to write, cols. If ‘cols’ is < 0, the entire struct will be written if possible. Returns -1 if the ‘e’ doesn’t point to a struct, otherwise the number of columns written

将结构写入行r。 接受一个指向结构类型“ e”的指针,以及要写入的列数“ cols”。 如果’cols’<0,则将尽可能写入整个结构。 如果’e’不指向结构,则返回-1,否则返回写入的列数

xlsx.Col

Defination

type Col struct {
    Min          int
    Max          int
    Hidden       bool
    Width        float64
    Collapsed    bool
    OutlineLevel uint8
    BestFit      bool
    CustomWidth  bool
    Phonetic     bool
    // contains filtered or unexported fields
}

func NewColForRange(min, max int) *Col

NewColForRange return a pointer to a new Col, which will apply to columns in the range min to max (inclusive). Note, in order for this Col to do anything useful you must set some of its parameters and then apply it to a Sheet by calling sheet.SetColParameters.

NewColForRange返回一个指向新Col的指针,该指针将应用于min到max(含)范围内的列。 请注意,为了使此Col做任何有用的事情,您必须设置其一些参数,然后通过调用sheet.SetColParameters将其应用于Sheet。

func (c *Col) GetStyle() *Style

GetStyle returns the Style associated with a Col

func (c *Col) SetOutlineLevel(outlineLevel uint8)

func (c *Col) SetStyle(style *Style)

SetStyle sets the style of a Col

func (c *Col) SetType(cellType CellType)

SetType will set the format string of a column based on the type that you want to set it to. This function does not really make a lot of sense.

SetType将根据您要设置的类型设置列的格式字符串。 这个功能并没有多大意义。

func (c *Col) SetWidth(width float64)

SetWidth sets the width of columns that have this Col applied to them. The width is expressed as the number of characters of the maximum digit width of the numbers 0-9 as rendered in the normal style’s font.

SetWidth设置已应用此Col的列的宽度。 宽度表示为以常规样式的字体呈现的数字0-9的最大数字宽度的字符数。

xlsx.Cell

Defination

type Cell struct {
    Row   *Row
    Value string

    NumFmt string

    Hidden bool
    HMerge int
    VMerge int

    DataValidation *xlsxDataValidation
    Hyperlink      Hyperlink
    // contains filtered or unexported fields
}

Cell is a high level structure intended to provide user access to the contents of Cell within an xlsx.Row.

func (c *Cell) Bool() bool

Bool returns a boolean from a cell’s value. TODO: Determine if the current return value is appropriate for types other than CellTypeBool.

func (c *Cell) Float() (float64, error)

Float returns the value of cell as a number.

func (c *Cell) FormattedValue() (string, error)

FormattedValue returns a value, and possibly an error condition from a Cell. If it is possible to apply a format to the cell value, it will do so,
if not then an error will be returned, along with the raw value of the Cell.

GetStyle returns the Style associated with a Cell

FormattedValue返回一个值,并可能返回来自Cell的错误条件。 如果可以将格式应用于单元格值,则将这样做,否则将返回错误以及单元格的原始值。

GetTime returns the value of a Cell as a time.Time

func (c *Cell) Formula() string

Formula returns the formula string for the cell.

func (c *Cell) GeneralNumeric() (string, error)

GeneralNumeric returns the value of the cell as a string. It is formatted very closely to the the XLSX spec for how to display values when the storage type is Number and the format type is General. It is not 100% identical to the spec but is as close as you can get using the built in Go formatting tools.

GeneralNumeric以字符串形式返回单元格的值。 当存储类型为Number且格式类型为General时,它的格式与XLSX规范非常接近,以显示如何显示值。 它与规格不是100%相同,但与使用内置的Go格式设置工具所能达到的程度非常接近。

func (c *Cell) GeneralNumericWithoutScientific() (string, error)

GeneralNumericWithoutScientific returns numbers that are always formatted as numbers, but it does not follow the rules for when XLSX should switch to scientific notation, since sometimes scientific notation is not desired, even if that is how the document is supposed to be formatted.

GeneralNumericWithoutScientific返回始终以数字格式设置的数字,但是它不遵循XLSX何时应转换为科学计数法的规则,因为有时不希望使用科学计数法,即使文档应该采用这种格式。

func (c *Cell) GetNumberFormat() string

GetNumberFormat returns the number format string for a cell.

GetNumberFormat返回单元格的数字格式字符串。

func (c *Cell) GetStyle() *Style

GetStyle returns the Style associated with a Cell

func (c *Cell) GetTime(date1904 bool) (t time.Time, err error)

GetTime returns the value of a Cell as a time.Time

GetTime返回一个Cell的值作为时间。

func (c *Cell) Int() (int, error)

Int returns the value of cell as integer. Has max 53 bits of precision See: float64(int64(math.MaxInt))

func (c *Cell) Int64() (int64, error)

Int64 returns the value of cell as 64-bit integer.

func (c *Cell) IsTime() bool

IsTime returns true if the cell stores a time value.

func (c Cell) MarshalBinary() ([]byte, error)

Return a representation of the Cell as a slice of bytes

func (c *Cell) Merge(hcells, vcells int)

Merge with other cells, horizontally and/or vertically.

与其他单元格水平和/或垂直合并。

func (c *Cell) SetBool(b bool)

SetBool sets a cell’s value to a boolean.

func (c *Cell) SetDataValidation(dd *xlsxDataValidation)

SetDataValidation set data validation

func (c *Cell) SetDate(t time.Time)

SetDate sets the value of a cell to a float.

func (c *Cell) SetDateTime(t time.Time)

SetDateWithOptions allows for more granular control when exporting dates and times

func (c *Cell) SetDateTimeWithFormat(n float64, format string)

SetDateWithOptions allows for more granular control when exporting dates and times

func (c *Cell) SetDateWithOptions(t time.Time, options DateTimeOptions)

SetDateWithOptions allows for more granular control when exporting dates and times

func (c *Cell) SetFloat(n float64)

SetFloat sets the value of a cell to a float.

func (c *Cell) SetFloatWithFormat(n float64, format string)

SetFloatWithFormat sets the alue of a cell to a float and applies formatting to the cell.

func (c *Cell) SetFormat(format string)

SetCellFormat set cell value format

func (c *Cell) SetFormula(formula string)

SetFormula sets the format string for a cell.

func (c *Cell) SetHyperlink(hyperlink string, displayText string, tooltip string)

SetHyperlink sets this cell to contain the given hyperlink, displayText and tooltip. If the displayText or tooltip are an empty string, they will not be set. The hyperlink provided must be a valid URL starting with http:// or https:// or excel will not recognize it as an external link.

SetHyperlink将此单元格设置为包含给定的超链接,displayText和工具提示。 如果displayText或tooltip是空字符串,则不会设置它们。 提供的超链接必须是以http://或https://开头的有效URL,否则excel不会将其识别为外部链接。

func (c *Cell) SetInt(n int)

SetInt sets a cell’s value to an integer.

func (c *Cell) SetInt64(n int64)

SetInt64 sets a cell’s value to a 64-bit integer.

func (c *Cell) SetNumeric(s string)

SetNumeric sets a cell’s value to a number

func (c *Cell) SetString(s string)

SetString sets the value of a cell to a string.

func (c *Cell) SetStringFormula(formula string)

func (c *Cell) SetStyle(style *Style)

func (c *Cell) SetValue(n interface{})

SetInt sets a cell’s value to an integer.

func (c *Cell) String() string

String returns the value of a Cell as a string. If you’d like to see errors returned from formatting then please use Cell.FormattedValue() instead.

func (c *Cell) Type() CellType

Type returns the CellType of a cell. See CellType constants for more details.

func (c *Cell) UnmarshalBinary(data []byte) error

Read a slice of bytes, produced by MarshalBinary, into a Cell

Examples

create a sheet.


package main

import(
    "strconv"
    "fmt"
    "github.com/tealeg/xlsx"
)

var (
    inFile = "./student1.xlsx"
    outFile = "./out_student.xlsx"
)

type Student struct{
    Name string
    age int
    Phone string
    Gender string
    Mail string
}

func Export(){
    file := xlsx.NewFile()
    sheet, err := file.AddSheet("student_list")
    if err != nil {
        fmt.Printf(err.Error())
    }
    stus := getStudents()
    //add data
    for _, stu := range stus{
        row := sheet.AddRow()
        nameCell := row.AddCell()
        nameCell.Value = stu.Name

        ageCell := row.AddCell()
        ageCell.Value = strconv.Itoa(stu.age)

        phoneCell := row.AddCell()
        phoneCell.Value = stu.Phone

        genderCell := row.AddCell()
        genderCell.Value = stu.Gender

        mailCell := row.AddCell()
        mailCell.Value = stu.Mail
    }
    err = file.Save(outFile)
    if err != nil {
        fmt.Printf(err.Error())
    }
    fmt.Println("\n\nexport success")
}

func getStudents()[]Student{
    students := make([]Student, 0)
    for i := 0; i < 10; i++{
        stu := Student{}
        stu.Name = "name" + strconv.Itoa(i + 1)
        stu.Mail = stu.Name + "@chairis.cn"
        stu.Phone = "1380013800" + strconv.Itoa(i)
        stu.age = 20
        stu.Gender = "男"
        students = append(students, stu)
    }
    return students
}


func main(){
	Export()
}

Reference:

[1] https://godoc.org/github.com/tealeg/xlsx

你可能感兴趣的:(golang)