Go, how to copy data from on excel file to another

I couldn’t find a good example on this. For a project I am working on, I needed to be able to take an input excel document, xlsx to be specifc, and write the data to another excel file matching another standard for processing.

I am going to keep the commentary to a minimum, but here is an example of how you could read data from one xlsx file and write it to another. This example makes use of the “github.com/tealeg/xlsx” library.

More about the “github.com/tealeg/xlsx” library here.

My input file can be downloaded here from Google drive.

How to copy excel data to a new excel file.

package main

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

func main(){
    excelset := readExcel()
    writeExcel(excelset)
}


type person struct {
    firstName string
    lastName  string
}

func readExcel()(ret []person){
    var mySlice [][][]string
    var err error
    mySlice, err = xlsx.FileToSlice("originsheet.xlsx")
    if err != nil {
        fmt.Println("failed to read xlsx")
    }
    for _,sheet := range mySlice{
        for _, row := range sheet[1:]{
            p := person{firstName:row[0], lastName:row[1]}
            ret = append(ret,p)
        }
    }
    return ret
}
func writeExcel(ret []person){
    var excelFile *xlsx.File
    var sheet1 *xlsx.Sheet
    var err error

    excelFile = xlsx.NewFile()
    sheet1,err = excelFile.AddSheet("IB")
    if err != nil {
        fmt.Println("I failed to add a sheet")
    }
    for i,record := range ret{
        sheet1.AddRow()
        sheet1.Rows[i].AddCell()
        sheet1.Rows[i].Cells[0].SetString(record.firstName)
        sheet1.Rows[i].AddCell()
        sheet1.Rows[i].Cells[1].SetString(record.lastName)
    }
    excelFile.Save("resultFile.xlsx")
}