repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/termhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/termhandlers.go#L166-L180
go
train
// HandleShell handles requests of type "shell" which request a interactive // shell be created within a TTY.
func (t *TermHandlers) HandleShell(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
// HandleShell handles requests of type "shell" which request a interactive // shell be created within a TTY. func (t *TermHandlers) HandleShell(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
{ var err error // creating an empty exec request implies a interactive shell was requested ctx.ExecRequest, err = NewExecRequest(ctx, "") if err != nil { return trace.Wrap(err) } if err := t.SessionRegistry.OpenSession(ch, req, ctx); err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/termhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/termhandlers.go#L185-L199
go
train
// HandleWinChange handles requests of type "window-change" which update the // size of the PTY running on the server and update any other members in the // party.
func (t *TermHandlers) HandleWinChange(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
// HandleWinChange handles requests of type "window-change" which update the // size of the PTY running on the server and update any other members in the // party. func (t *TermHandlers) HandleWinChange(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error
{ params, err := parseWinChange(req) if err != nil { return trace.Wrap(err) } // Update any other members in the party that the window size has changed // and to update their terminal windows accordingly. err = t.SessionRegistry.NotifyWinChange(*params, ctx) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L176-L212
go
train
// CheckAndSetDefaults checks parameters and sets default values
func (cfg *Config) CheckAndSetDefaults() error
// CheckAndSetDefaults checks parameters and sets default values func (cfg *Config) CheckAndSetDefaults() error
{ if cfg.ID == "" { return trace.BadParameter("missing parameter ID") } if cfg.ClusterName == "" { return trace.BadParameter("missing parameter ClusterName") } if cfg.ClientTLS == nil { return trace.BadParameter("missing parameter ClientTLS") } if cfg.Listener == nil { return trace.BadParameter("missing parameter Listener") } if cfg.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if cfg.Context == nil { cfg.Context = context.TODO() } if cfg.PollingPeriod == 0 { cfg.PollingPeriod = defaults.HighResPollingPeriod } if cfg.Limiter == nil { var err error cfg.Limiter, err = limiter.NewLimiter(limiter.LimiterConfig{}) if err != nil { return trace.Wrap(err) } } if cfg.Clock == nil { cfg.Clock = clockwork.NewRealClock() } if cfg.Component == "" { cfg.Component = teleport.Component(teleport.ComponentProxy, teleport.ComponentServer) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L216-L268
go
train
// NewServer creates and returns a reverse tunnel server which is fully // initialized but hasn't been started yet
func NewServer(cfg Config) (Server, error)
// NewServer creates and returns a reverse tunnel server which is fully // initialized but hasn't been started yet func NewServer(cfg Config) (Server, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) srv := &server{ Config: cfg, localSites: []*localSite{}, remoteSites: []*remoteSite{}, localAuthClient: cfg.LocalAuthClient, localAccessPoint: cfg.LocalAccessPoint, newAccessPoint: cfg.NewCachingAccessPoint, limiter: cfg.Limiter, ctx: ctx, cancel: cancel, clusterPeers: make(map[string]*clusterPeers), Entry: log.WithFields(log.Fields{ trace.Component: cfg.Component, }), } for _, clusterInfo := range cfg.DirectClusters { cluster, err := newlocalSite(srv, clusterInfo.Name, clusterInfo.Client) if err != nil { return nil, trace.Wrap(err) } srv.localSites = append(srv.localSites, cluster) } var err error s, err := sshutils.NewServer( teleport.ComponentReverseTunnelServer, // TODO(klizhentas): improve interface, use struct instead of parameter list // this address is not used utils.NetAddr{Addr: "127.0.0.1:1", AddrNetwork: "tcp"}, srv, cfg.HostSigners, sshutils.AuthMethods{ PublicKey: srv.keyAuth, }, sshutils.SetLimiter(cfg.Limiter), sshutils.SetCiphers(cfg.Ciphers), sshutils.SetKEXAlgorithms(cfg.KEXAlgorithms), sshutils.SetMACAlgorithms(cfg.MACAlgorithms), ) if err != nil { return nil, err } srv.srv = s go srv.periodicFunctions() return srv, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L281-L302
go
train
// disconnectClusters disconnects reverse tunnel connections from remote clusters // that were deleted from the the local cluster side and cleans up in memory objects. // In this case all local trust has been deleted, so all the tunnel connections have to be dropped.
func (s *server) disconnectClusters() error
// disconnectClusters disconnects reverse tunnel connections from remote clusters // that were deleted from the the local cluster side and cleans up in memory objects. // In this case all local trust has been deleted, so all the tunnel connections have to be dropped. func (s *server) disconnectClusters() error
{ connectedRemoteClusters := s.getRemoteClusters() if len(connectedRemoteClusters) == 0 { return nil } remoteClusters, err := s.localAuthClient.GetRemoteClusters() if err != nil { return trace.Wrap(err) } remoteMap := remoteClustersMap(remoteClusters) for _, cluster := range connectedRemoteClusters { if _, ok := remoteMap[cluster.GetName()]; !ok { s.Infof("Remote cluster %q has been deleted. Disconnecting it from the proxy.", cluster.GetName()) s.RemoveSite(cluster.GetName()) err := cluster.Close() if err != nil { s.Debugf("Failure closing cluster %q: %v.", cluster.GetName(), err) } } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L337-L360
go
train
// fetchClusterPeers pulls back all proxies that have registered themselves // (created a services.TunnelConnection) in the backend and compares them to // what was found in the previous iteration and updates the in-memory cluster // peer map. This map is used later by GetSite(s) to return either local or // remote site, or if non match, a cluster peer.
func (s *server) fetchClusterPeers() error
// fetchClusterPeers pulls back all proxies that have registered themselves // (created a services.TunnelConnection) in the backend and compares them to // what was found in the previous iteration and updates the in-memory cluster // peer map. This map is used later by GetSite(s) to return either local or // remote site, or if non match, a cluster peer. func (s *server) fetchClusterPeers() error
{ conns, err := s.LocalAccessPoint.GetAllTunnelConnections() if err != nil { return trace.Wrap(err) } newConns := make(map[string]services.TunnelConnection) for i := range conns { newConn := conns[i] // Filter out node tunnels. if newConn.GetType() == services.NodeTunnel { continue } // Filter out peer records for own proxy. if newConn.GetProxyName() == s.ID { continue } newConns[newConn.GetName()] = newConn } existingConns := s.existingConns() connsToAdd, connsToUpdate, connsToRemove := s.diffConns(newConns, existingConns) s.removeClusterPeers(connsToRemove) s.updateClusterPeers(connsToUpdate) return s.addClusterPeers(connsToAdd) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L618-L630
go
train
// isHostAuthority is called during checking the client key, to see if the signing // key is the real host CA authority key.
func (s *server) isHostAuthority(auth ssh.PublicKey, address string) bool
// isHostAuthority is called during checking the client key, to see if the signing // key is the real host CA authority key. func (s *server) isHostAuthority(auth ssh.PublicKey, address string) bool
{ keys, err := s.getTrustedCAKeys(services.HostCA) if err != nil { s.Errorf("failed to retrieve trusted keys, err: %v", err) return false } for _, k := range keys { if sshutils.KeysEqual(k, auth) { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L634-L646
go
train
// isUserAuthority is called during checking the client key, to see if the signing // key is the real user CA authority key.
func (s *server) isUserAuthority(auth ssh.PublicKey) bool
// isUserAuthority is called during checking the client key, to see if the signing // key is the real user CA authority key. func (s *server) isUserAuthority(auth ssh.PublicKey) bool
{ keys, err := s.getTrustedCAKeys(services.UserCA) if err != nil { s.Errorf("failed to retrieve trusted keys, err: %v", err) return false } for _, k := range keys { if sshutils.KeysEqual(k, auth) { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L718-L751
go
train
// checkHostCert verifies that host certificate is signed // by the recognized certificate authority
func (s *server) checkHostCert(logger *log.Entry, user string, clusterName string, cert *ssh.Certificate) error
// checkHostCert verifies that host certificate is signed // by the recognized certificate authority func (s *server) checkHostCert(logger *log.Entry, user string, clusterName string, cert *ssh.Certificate) error
{ if cert.CertType != ssh.HostCert { return trace.BadParameter("expected host cert, got wrong cert type: %d", cert.CertType) } // fetch keys of the certificate authority to check // if there is a match keys, err := s.getTrustedCAKeysByID(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName, }) if err != nil { return trace.Wrap(err) } // match key of the certificate authority with the signature key var match bool for _, k := range keys { if sshutils.KeysEqual(k, cert.SignatureKey) { match = true break } } if !match { return trace.NotFound("cluster %v has no matching CA keys", clusterName) } checker := utils.CertChecker{} if err := checker.CheckCert(user, cert); err != nil { return trace.BadParameter(err.Error()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L855-L874
go
train
// GetSite returns a RemoteSite. The first attempt is to find and return a // remote site and that is what is returned if a remote remote agent has // connected to this proxy. Next we loop over local sites and try and try and // return a local site. If that fails, we return a cluster peer. This happens // when you hit proxy that has never had an agent connect to it. If you end up // with a cluster peer your best bet is to wait until the agent has discovered // all proxies behind a the load balancer. Note, the cluster peer is a // services.TunnelConnection that was created by another proxy.
func (s *server) GetSite(name string) (RemoteSite, error)
// GetSite returns a RemoteSite. The first attempt is to find and return a // remote site and that is what is returned if a remote remote agent has // connected to this proxy. Next we loop over local sites and try and try and // return a local site. If that fails, we return a cluster peer. This happens // when you hit proxy that has never had an agent connect to it. If you end up // with a cluster peer your best bet is to wait until the agent has discovered // all proxies behind a the load balancer. Note, the cluster peer is a // services.TunnelConnection that was created by another proxy. func (s *server) GetSite(name string) (RemoteSite, error)
{ s.RLock() defer s.RUnlock() for i := range s.remoteSites { if s.remoteSites[i].GetName() == name { return s.remoteSites[i], nil } } for i := range s.localSites { if s.localSites[i].GetName() == name { return s.localSites[i], nil } } for i := range s.clusterPeers { if s.clusterPeers[i].GetName() == name { return s.clusterPeers[i], nil } } return nil, trace.NotFound("cluster %q is not found", name) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/srv.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/srv.go#L895-L956
go
train
// newRemoteSite helper creates and initializes 'remoteSite' instance
func newRemoteSite(srv *server, domainName string) (*remoteSite, error)
// newRemoteSite helper creates and initializes 'remoteSite' instance func newRemoteSite(srv *server, domainName string) (*remoteSite, error)
{ connInfo, err := services.NewTunnelConnection( fmt.Sprintf("%v-%v", srv.ID, domainName), services.TunnelConnectionSpecV2{ ClusterName: domainName, ProxyName: srv.ID, LastHeartbeat: time.Now().UTC(), }, ) if err != nil { return nil, trace.Wrap(err) } closeContext, cancel := context.WithCancel(srv.ctx) remoteSite := &remoteSite{ srv: srv, domainName: domainName, connInfo: connInfo, Entry: log.WithFields(log.Fields{ trace.Component: teleport.ComponentReverseTunnelServer, trace.ComponentFields: log.Fields{ "cluster": domainName, }, }), ctx: closeContext, cancel: cancel, clock: srv.Clock, } // configure access to the full Auth Server API and the cached subset for // the local cluster within which reversetunnel.Server is running. remoteSite.localClient = srv.localAuthClient remoteSite.localAccessPoint = srv.localAccessPoint clt, _, err := remoteSite.getRemoteClient() if err != nil { return nil, trace.Wrap(err) } remoteSite.remoteClient = clt // configure access to the cached subset of the Auth Server API of the remote // cluster this remote site provides access to. accessPoint, err := srv.newAccessPoint(clt, []string{"reverse", domainName}) if err != nil { return nil, trace.Wrap(err) } remoteSite.remoteAccessPoint = accessPoint // instantiate a cache of host certificates for the forwarding server. the // certificate cache is created in each site (instead of creating it in // reversetunnel.server and passing it along) so that the host certificate // is signed by the correct certificate authority. certificateCache, err := NewHostCertificateCache(srv.Config.KeyGen, srv.localAuthClient) if err != nil { return nil, trace.Wrap(err) } remoteSite.certificateCache = certificateCache go remoteSite.periodicUpdateCertAuthorities() return remoteSite, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
xmlWorksheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/xmlWorksheet.go#L312-L331
go
train
// Return the cartesian extent of a merged cell range from its origin // cell (the closest merged cell to the to left of the sheet.
func (mc *xlsxMergeCells) getExtent(cellRef string) (int, int, error)
// Return the cartesian extent of a merged cell range from its origin // cell (the closest merged cell to the to left of the sheet. func (mc *xlsxMergeCells) getExtent(cellRef string) (int, int, error)
{ if mc == nil { return 0, 0, nil } for _, cell := range mc.Cells { if strings.HasPrefix(cell.Ref, cellRef+cellRangeChar) { parts := strings.Split(cell.Ref, cellRangeChar) startx, starty, err := GetCoordsFromCellIDString(parts[0]) if err != nil { return -1, -1, err } endx, endy, err := GetCoordsFromCellIDString(parts[1]) if err != nil { return -2, -2, err } return endx - startx, endy - starty, nil } } return 0, 0, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
col.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/col.go#L23-L42
go
train
// 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.
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. func (c *Col) SetType(cellType CellType)
{ switch cellType { case CellTypeString: c.numFmt = builtInNumFmt[builtInNumFmtIndex_STRING] case CellTypeNumeric: c.numFmt = builtInNumFmt[builtInNumFmtIndex_INT] case CellTypeBool: c.numFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] //TEMP case CellTypeInline: c.numFmt = builtInNumFmt[builtInNumFmtIndex_STRING] case CellTypeError: c.numFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] //TEMP case CellTypeDate: // Cells that are stored as dates are not properly supported in this library. // They should instead be stored as a Numeric with a date format. c.numFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] case CellTypeStringFormula: c.numFmt = builtInNumFmt[builtInNumFmtIndex_STRING] } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
col.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/col.go#L56-L93
go
train
// SetDataValidation set data validation with zero based start and end. // Set end to -1 for all rows.
func (c *Col) SetDataValidation(dd *xlsxCellDataValidation, start, end int)
// SetDataValidation set data validation with zero based start and end. // Set end to -1 for all rows. func (c *Col) SetDataValidation(dd *xlsxCellDataValidation, start, end int)
{ if end < 0 { end = Excel2006MaxRowIndex } dd.minRow = start dd.maxRow = end tmpDD := make([]*xlsxCellDataValidation, 0) for _, item := range c.DataValidation { if item.maxRow < dd.minRow { tmpDD = append(tmpDD, item) //No intersection } else if item.minRow > dd.maxRow { tmpDD = append(tmpDD, item) //No intersection } else if dd.minRow <= item.minRow && dd.maxRow >= item.maxRow { continue //union , item can be ignored } else if dd.minRow >= item.minRow { //Split into three or two, Newly added object, intersect with the current object in the lower half tmpSplit := new(xlsxCellDataValidation) *tmpSplit = *item if dd.minRow > item.minRow { //header whetherneed to split item.maxRow = dd.minRow - 1 tmpDD = append(tmpDD, item) } if dd.maxRow < tmpSplit.maxRow { //footer whetherneed to split tmpSplit.minRow = dd.maxRow + 1 tmpDD = append(tmpDD, tmpSplit) } } else { item.minRow = dd.maxRow + 1 tmpDD = append(tmpDD, item) } } tmpDD = append(tmpDD, dd) c.DataValidation = tmpDD }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
col.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/col.go#L97-L99
go
train
// SetDataValidationWithStart set data validation with a zero basd start row. // This will apply to the rest of the rest of the column.
func (c *Col) SetDataValidationWithStart(dd *xlsxCellDataValidation, start int)
// SetDataValidationWithStart set data validation with a zero basd start row. // This will apply to the rest of the rest of the column. func (c *Col) SetDataValidationWithStart(dd *xlsxCellDataValidation, start int)
{ c.SetDataValidation(dd, start, -1) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
date.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/date.go#L104-L128
go
train
// Convert an excelTime representation (stored as a floating point number) to a time.Time.
func TimeFromExcelTime(excelTime float64, date1904 bool) time.Time
// Convert an excelTime representation (stored as a floating point number) to a time.Time. func TimeFromExcelTime(excelTime float64, date1904 bool) time.Time
{ var date time.Time var wholeDaysPart = int(excelTime) // Excel uses Julian dates prior to March 1st 1900, and // Gregorian thereafter. if wholeDaysPart <= 61 { const OFFSET1900 = 15018.0 const OFFSET1904 = 16480.0 var date time.Time if date1904 { date = julianDateToGregorianTime(MJD_0, excelTime+OFFSET1904) } else { date = julianDateToGregorianTime(MJD_0, excelTime+OFFSET1900) } return date } var floatPart = excelTime - float64(wholeDaysPart) if date1904 { date = excel1904Epoc } else { date = excel1900Epoc } durationPart := time.Duration(nanosInADay * floatPart) return date.AddDate(0,0, wholeDaysPart).Add(durationPart) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
date.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/date.go#L133-L147
go
train
// TimeToExcelTime will convert a time.Time into Excel's float representation, in either 1900 or 1904 // mode. If you don't know which to use, set date1904 to false. // TODO should this should handle Julian dates?
func TimeToExcelTime(t time.Time, date1904 bool) float64
// TimeToExcelTime will convert a time.Time into Excel's float representation, in either 1900 or 1904 // mode. If you don't know which to use, set date1904 to false. // TODO should this should handle Julian dates? func TimeToExcelTime(t time.Time, date1904 bool) float64
{ // Get the number of days since the unix epoc daysSinceUnixEpoc := float64(t.Unix())/secondsInADay // Get the number of nanoseconds in days since Unix() is in seconds. nanosPart := float64(t.Nanosecond())/nanosInADay // Add both together plus the number of days difference between unix and Excel epocs. var offsetDays float64 if date1904 { offsetDays = daysBetween1970And1904 } else { offsetDays = daysBetween1970And1900 } daysSinceExcelEpoc := daysSinceUnixEpoc + offsetDays + nanosPart return daysSinceExcelEpoc }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
xmlWorkbook.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/xmlWorkbook.go#L182-L213
go
train
// getWorksheetFromSheet() is an internal helper function to open a // sheetN.xml file, referred to by an xlsx.xlsxSheet struct, from the XLSX // file and unmarshal it an xlsx.xlsxWorksheet struct
func getWorksheetFromSheet(sheet xlsxSheet, worksheets map[string]*zip.File, sheetXMLMap map[string]string, rowLimit int) (*xlsxWorksheet, error)
// getWorksheetFromSheet() is an internal helper function to open a // sheetN.xml file, referred to by an xlsx.xlsxSheet struct, from the XLSX // file and unmarshal it an xlsx.xlsxWorksheet struct func getWorksheetFromSheet(sheet xlsxSheet, worksheets map[string]*zip.File, sheetXMLMap map[string]string, rowLimit int) (*xlsxWorksheet, error)
{ var r io.Reader var decoder *xml.Decoder var worksheet *xlsxWorksheet var err error worksheet = new(xlsxWorksheet) f := worksheetFileForSheet(sheet, worksheets, sheetXMLMap) if f == nil { return nil, fmt.Errorf("Unable to find sheet '%s'", sheet) } if rc, err := f.Open(); err != nil { return nil, err } else { defer rc.Close() r = rc } if rowLimit != NoRowLimit { r, err = truncateSheetXML(r, rowLimit) if err != nil { return nil, err } } decoder = xml.NewDecoder(r) err = decoder.Decode(worksheet) if err != nil { return nil, err } return worksheet, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L58-L65
go
train
// NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer
func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder
// NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder
{ return &StreamFileBuilder{ zipWriter: zip.NewWriter(writer), xlsxFile: NewFile(), cellTypeToStyleIds: make(map[CellType]int), maxStyleId: initMaxStyleId, } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L69-L75
go
train
// NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it. // The file will be created if it does not exist, or truncated if it does.
func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error)
// NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it. // The file will be created if it does not exist, or truncated if it does. func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error)
{ file, err := os.Create(path) if err != nil { return nil, err } return NewStreamFileBuilder(file), nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L80-L120
go
train
// AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all // rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an // error will be thrown.
func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellTypes []*CellType) error
// AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all // rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an // error will be thrown. func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellTypes []*CellType) error
{ if sb.built { return BuiltStreamFileBuilderError } if len(cellTypes) > len(headers) { return errors.New("cellTypes is longer than headers") } sheet, err := sb.xlsxFile.AddSheet(name) if err != nil { // Set built on error so that all subsequent calls to the builder will also fail. sb.built = true return err } sb.styleIds = append(sb.styleIds, []int{}) row := sheet.AddRow() if count := row.WriteSlice(&headers, -1); count != len(headers) { // Set built on error so that all subsequent calls to the builder will also fail. sb.built = true return errors.New("failed to write headers") } for i, cellType := range cellTypes { var cellStyleIndex int var ok bool if cellType != nil { // The cell type is one of the attributes of a Style. // Since it is the only attribute of Style that we use, we can assume that cell types // map one to one with Styles and their Style ID. // If a new cell type is used, a new style gets created with an increased id, if an existing cell type is // used, the pre-existing style will also be used. cellStyleIndex, ok = sb.cellTypeToStyleIds[*cellType] if !ok { sb.maxStyleId++ cellStyleIndex = sb.maxStyleId sb.cellTypeToStyleIds[*cellType] = sb.maxStyleId } sheet.Cols[i].SetType(*cellType) } sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex) } return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L123-L127
go
train
// AddValidation will add a validation to a specific column.
func (sb *StreamFileBuilder) AddValidation(sheetIndex, colIndex, rowStartIndex int, validation *xlsxCellDataValidation)
// AddValidation will add a validation to a specific column. func (sb *StreamFileBuilder) AddValidation(sheetIndex, colIndex, rowStartIndex int, validation *xlsxCellDataValidation)
{ sheet := sb.xlsxFile.Sheets[sheetIndex] column := sheet.Col(colIndex) column.SetDataValidationWithStart(validation, rowStartIndex) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L131-L170
go
train
// Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct // that can be used to write the rows to the sheets.
func (sb *StreamFileBuilder) Build() (*StreamFile, error)
// Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct // that can be used to write the rows to the sheets. func (sb *StreamFileBuilder) Build() (*StreamFile, error)
{ if sb.built { return nil, BuiltStreamFileBuilderError } sb.built = true parts, err := sb.xlsxFile.MarshallParts() if err != nil { return nil, err } es := &StreamFile{ zipWriter: sb.zipWriter, xlsxFile: sb.xlsxFile, sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)), sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)), styleIds: sb.styleIds, } for path, data := range parts { // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this // point the sheets are still empty. The sheet files will be written later as their rows come in. if strings.HasPrefix(path, sheetFilePathPrefix) { if err := sb.processEmptySheetXML(es, path, data); err != nil { return nil, err } continue } metadataFile, err := sb.zipWriter.Create(path) if err != nil { return nil, err } _, err = metadataFile.Write([]byte(data)) if err != nil { return nil, err } } if err := es.NextSheet(); err != nil { return nil, err } return es, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L174-L196
go
train
// processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the // XML file so that these can be written at the right time.
func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error
// processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the // XML file so that these can be written at the right time. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error
{ // Get the sheet index from the path sheetIndex, err := getSheetIndex(sf, path) if err != nil { return err } // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex]) if err != nil { return err } // Split the sheet at the end of its SheetData tag so that more rows can be added inside. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data) if err != nil { return err } sf.sheetXmlPrefix[sheetIndex] = prefix sf.sheetXmlSuffix[sheetIndex] = suffix return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L202-L214
go
train
// getSheetIndex parses the path to the XLSX sheet data and returns the index // The files that store the data for each sheet must have the format: // xl/worksheets/sheet123.xml // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
func getSheetIndex(sf *StreamFile, path string) (int, error)
// getSheetIndex parses the path to the XLSX sheet data and returns the index // The files that store the data for each sheet must have the format: // xl/worksheets/sheet123.xml // where 123 is the index of the sheet. This file path format is part of the XLSX file standard. func getSheetIndex(sf *StreamFile, path string) (int, error)
{ indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)] sheetXLSXIndex, err := strconv.Atoi(indexString) if err != nil { return -1, errors.New("Unexpected sheet file name from xlsx package") } if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex || len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex { return -1, errors.New("Unexpected sheet index") } sheetArrayIndex := sheetXLSXIndex - 1 return sheetArrayIndex, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L220-L241
go
train
// removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed. // data is the XML data for the sheet // sheet is the Sheet struct that the XML was created from. // Can return an error if the XML's dimension tag does not match was is expected based on the provided Sheet
func removeDimensionTag(data string, sheet *Sheet) (string, error)
// removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed. // data is the XML data for the sheet // sheet is the Sheet struct that the XML was created from. // Can return an error if the XML's dimension tag does not match was is expected based on the provided Sheet func removeDimensionTag(data string, sheet *Sheet) (string, error)
{ x := len(sheet.Cols) - 1 y := len(sheet.Rows) - 1 if x < 0 { x = 0 } if y < 0 { y = 0 } var dimensionRef string if x == 0 && y == 0 { dimensionRef = "A1" } else { endCoordinate := GetCellIDStringFromCoords(x, y) dimensionRef = "A1:" + endCoordinate } dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef)) if len(dataParts) != 2 { return "", errors.New("unexpected Sheet XML: dimension tag not found") } return dataParts[0] + dataParts[1], nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file_builder.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file_builder.go#L245-L252
go
train
// splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that // more spreadsheet rows can be inserted in between.
func splitSheetIntoPrefixAndSuffix(data string) (string, string, error)
// splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that // more spreadsheet rows can be inserted in between. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error)
{ // Split the sheet at the end of its SheetData tag so that more rows can be added inside. sheetParts := strings.Split(data, endSheetDataTag) if len(sheetParts) != 2 { return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found") } return sheetParts[0], sheetParts[1], nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L42-L52
go
train
// Write will write a row of cells to the current sheet. Every call to Write on the same sheet must contain the // same number of cells as the header provided when the sheet was created or an error will be returned. This function // will always trigger a flush on success. Currently the only supported data type is string data.
func (sf *StreamFile) Write(cells []string) error
// Write will write a row of cells to the current sheet. Every call to Write on the same sheet must contain the // same number of cells as the header provided when the sheet was created or an error will be returned. This function // will always trigger a flush on success. Currently the only supported data type is string data. func (sf *StreamFile) Write(cells []string) error
{ if sf.err != nil { return sf.err } err := sf.write(cells) if err != nil { sf.err = err return err } return sf.zipWriter.Flush() }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L128-L165
go
train
// NextSheet will switch to the next sheet. Sheets are selected in the same order they were added. // Once you leave a sheet, you cannot return to it.
func (sf *StreamFile) NextSheet() error
// NextSheet will switch to the next sheet. Sheets are selected in the same order they were added. // Once you leave a sheet, you cannot return to it. func (sf *StreamFile) NextSheet() error
{ if sf.err != nil { return sf.err } var sheetIndex int if sf.currentSheet != nil { if sf.currentSheet.index >= len(sf.xlsxFile.Sheets) { sf.err = AlreadyOnLastSheetError return AlreadyOnLastSheetError } if err := sf.writeSheetEnd(); err != nil { sf.currentSheet = nil sf.err = err return err } sheetIndex = sf.currentSheet.index } sheetIndex++ sf.currentSheet = &streamSheet{ index: sheetIndex, columnCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Cols), styleIds: sf.styleIds[sheetIndex-1], rowCount: 1, } sheetPath := sheetFilePathPrefix + strconv.Itoa(sf.currentSheet.index) + sheetFilePathSuffix fileWriter, err := sf.zipWriter.Create(sheetPath) if err != nil { sf.err = err return err } sf.currentSheet.writer = fileWriter if err := sf.writeSheetStart(); err != nil { sf.err = err return err } return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L169-L193
go
train
// Close closes the Stream File. // Any sheets that have not yet been written to will have an empty sheet created for them.
func (sf *StreamFile) Close() error
// Close closes the Stream File. // Any sheets that have not yet been written to will have an empty sheet created for them. func (sf *StreamFile) Close() error
{ if sf.err != nil { return sf.err } // If there are sheets that have not been written yet, call NextSheet() which will add files to the zip for them. // XLSX readers may error if the sheets registered in the metadata are not present in the file. if sf.currentSheet != nil { for sf.currentSheet.index < len(sf.xlsxFile.Sheets) { if err := sf.NextSheet(); err != nil { sf.err = err return err } } // Write the end of the last sheet. if err := sf.writeSheetEnd(); err != nil { sf.err = err return err } } err := sf.zipWriter.Close() if err != nil { sf.err = err } return err }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L196-L201
go
train
// writeSheetStart will write the start of the Sheet's XML
func (sf *StreamFile) writeSheetStart() error
// writeSheetStart will write the start of the Sheet's XML func (sf *StreamFile) writeSheetStart() error
{ if sf.currentSheet == nil { return NoCurrentSheetError } return sf.currentSheet.write(sf.sheetXmlPrefix[sf.currentSheet.index-1]) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
stream_file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/stream_file.go#L204-L212
go
train
// writeSheetEnd will write the end of the Sheet's XML
func (sf *StreamFile) writeSheetEnd() error
// writeSheetEnd will write the end of the Sheet's XML func (sf *StreamFile) writeSheetEnd() error
{ if sf.currentSheet == nil { return NoCurrentSheetError } if err := sf.currentSheet.write(endSheetDataTag); err != nil { return err } return sf.currentSheet.write(sf.sheetXmlSuffix[sf.currentSheet.index-1]) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
format_code.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L69-L113
go
train
// FormatValue 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. // // This is the documentation of the "General" Format in the Office Open XML spec: // // Numbers // The application shall attempt to display the full number up to 11 digits (inc. decimal point). If the number is too // large*, the application shall attempt to show exponential format. If the number has too many significant digits, the // display shall be truncated. The optimal method of display is based on the available cell width. If the number cannot // be displayed using any of these formats in the available width, the application shall show "#" across the width of // the cell. // // Conditions for switching to exponential format: // 1. The cell value shall have at least five digits for xE-xx // 2. If the exponent is bigger than the size allowed, a floating point number cannot fit, so try exponential notation. // 3. Similarly, for negative exponents, check if there is space for even one (non-zero) digit in floating point format**. // 4. Finally, if there isn't room for all of the significant digits in floating point format (for a negative exponent), // exponential format shall display more digits if the exponent is less than -3. (The 3 is because E-xx takes 4 // characters, and the leading 0 in floating point takes only 1 character. Thus, for an exponent less than -3, there is // more than 3 additional leading 0's, more than enough to compensate for the size of the E-xx.) // // Floating point rule: // For general formatting in cells, max overall length for cell display is 11, not including negative sign, but includes // leading zeros and decimal separator.*** // // Added Notes: // * "If the number is too large" can also mean "if the number has more than 11 digits", so greater than or equal to // 1e11 and less than 1e-9. // ** Means that you should switch to scientific if there would be 9 zeros after the decimal (the decimal and first zero // count against the 11 character limit), so less than 1e9. // *** The way this is written, you can get numbers that are more than 11 characters because the golang Float fmt // does not support adjusting the precision while not padding with zeros, while also not switching to scientific // notation too early.
func (fullFormat *parsedNumberFormat) FormatValue(cell *Cell) (string, error)
// FormatValue 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. // // This is the documentation of the "General" Format in the Office Open XML spec: // // Numbers // The application shall attempt to display the full number up to 11 digits (inc. decimal point). If the number is too // large*, the application shall attempt to show exponential format. If the number has too many significant digits, the // display shall be truncated. The optimal method of display is based on the available cell width. If the number cannot // be displayed using any of these formats in the available width, the application shall show "#" across the width of // the cell. // // Conditions for switching to exponential format: // 1. The cell value shall have at least five digits for xE-xx // 2. If the exponent is bigger than the size allowed, a floating point number cannot fit, so try exponential notation. // 3. Similarly, for negative exponents, check if there is space for even one (non-zero) digit in floating point format**. // 4. Finally, if there isn't room for all of the significant digits in floating point format (for a negative exponent), // exponential format shall display more digits if the exponent is less than -3. (The 3 is because E-xx takes 4 // characters, and the leading 0 in floating point takes only 1 character. Thus, for an exponent less than -3, there is // more than 3 additional leading 0's, more than enough to compensate for the size of the E-xx.) // // Floating point rule: // For general formatting in cells, max overall length for cell display is 11, not including negative sign, but includes // leading zeros and decimal separator.*** // // Added Notes: // * "If the number is too large" can also mean "if the number has more than 11 digits", so greater than or equal to // 1e11 and less than 1e-9. // ** Means that you should switch to scientific if there would be 9 zeros after the decimal (the decimal and first zero // count against the 11 character limit), so less than 1e9. // *** The way this is written, you can get numbers that are more than 11 characters because the golang Float fmt // does not support adjusting the precision while not padding with zeros, while also not switching to scientific // notation too early. func (fullFormat *parsedNumberFormat) FormatValue(cell *Cell) (string, error)
{ switch cell.cellType { case CellTypeError: // The error type is what XLSX uses in error cases such as when formulas are invalid. // There will be text in the cell's value that can be shown, something ugly like #NAME? or ####### return cell.Value, nil case CellTypeBool: if cell.Value == "0" { return "FALSE", nil } else if cell.Value == "1" { return "TRUE", nil } else { return cell.Value, errors.New("invalid value in bool cell") } case CellTypeString: fallthrough case CellTypeInline: fallthrough case CellTypeStringFormula: textFormat := cell.parsedNumFmt.textFormat // This switch statement is only for String formats switch textFormat.reducedFormatString { case builtInNumFmt[builtInNumFmtIndex_GENERAL]: // General is literally "general" return cell.Value, nil case builtInNumFmt[builtInNumFmtIndex_STRING]: // String is "@" return textFormat.prefix + cell.Value + textFormat.suffix, nil case "": // If cell is not "General" and there is not an "@" symbol in the format, then the cell's value is not // used when determining what to display. It would be completely legal to have a format of "Error" // for strings, and all values that are not numbers would show up as "Error". In that case, this code would // have a prefix of "Error" and a reduced format string of "" (empty string). return textFormat.prefix + textFormat.suffix, nil default: return cell.Value, errors.New("invalid or unsupported format, unsupported string format") } case CellTypeDate: // These are dates that are stored in date format instead of being stored as numbers with a format to turn them // into a date string. return cell.Value, nil case CellTypeNumeric: return fullFormat.formatNumericCell(cell) default: return cell.Value, errors.New("unknown cell type") } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
format_code.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L224-L235
go
train
// Format strings are a little strange to compare because empty string needs to be taken as general, and general needs // to be compared case insensitively.
func compareFormatString(fmt1, fmt2 string) bool
// Format strings are a little strange to compare because empty string needs to be taken as general, and general needs // to be compared case insensitively. func compareFormatString(fmt1, fmt2 string) bool
{ if fmt1 == fmt2 { return true } if fmt1 == "" || strings.EqualFold(fmt1, "general") { fmt1 = "general" } if fmt2 == "" || strings.EqualFold(fmt2, "general") { fmt2 = "general" } return fmt1 == fmt2 }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
format_code.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L315-L334
go
train
// splitFormatOnSemicolon will split the format string into the format sections // This logic to split the different formats on semicolon is fully correct, and will skip all literal semicolons, // and will catch all breaking semicolons.
func splitFormatOnSemicolon(format string) ([]string, error)
// splitFormatOnSemicolon will split the format string into the format sections // This logic to split the different formats on semicolon is fully correct, and will skip all literal semicolons, // and will catch all breaking semicolons. func splitFormatOnSemicolon(format string) ([]string, error)
{ var formats []string prevIndex := 0 for i := 0; i < len(format); i++ { if format[i] == ';' { formats = append(formats, format[prevIndex:i]) prevIndex = i + 1 } else if format[i] == '\\' { i++ } else if format[i] == '"' { endQuoteIndex := strings.Index(format[i+1:], "\"") if endQuoteIndex == -1 { // This is an invalid format string, fall back to general return nil, errors.New("invalid format string, unmatched double quote") } i += endQuoteIndex + 1 } } return append(formats, format[prevIndex:]), nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
format_code.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L360-L398
go
train
// parseNumberFormatSection takes in individual format and parses out most of the options. // Some options are parsed, removed from the string, and set as settings on formatOptions. // There remainder of the format string is put in the reducedFormatString attribute, and supported values for these // are handled in a switch in the Cell.FormattedValue() function. // Ideally more and more of the format string would be parsed out here into settings until there is no remainder string // at all. // Features that this supports: // - Time formats are detected, and marked in the options. Time format strings are handled when doing the formatting. // The logic to detect time formats is currently not correct, and can catch formats that are not time formats as well // as miss formats that are time formats. // - Color formats are detected and removed. // - Currency annotations are handled properly. // - Literal strings wrapped in quotes are handled and put into prefix or suffix. // - Numbers that should be percent are detected and marked in the options. // - Conditionals are detected and removed, but they are not obeyed. The conditional groups will be used just like the // positive;negative;zero;string format groups. Here is an example of a conditional format: "[Red][<=100];[Blue][>100]" // Decoding the actual number formatting portion is out of scope, that is placed into reducedFormatString and is used // when formatting the string. The string there will be reduced to only the things in the formattingCharacters array. // Everything not in that array has been parsed out and put into formatOptions.
func parseNumberFormatSection(fullFormat string) (*formatOptions, error)
// parseNumberFormatSection takes in individual format and parses out most of the options. // Some options are parsed, removed from the string, and set as settings on formatOptions. // There remainder of the format string is put in the reducedFormatString attribute, and supported values for these // are handled in a switch in the Cell.FormattedValue() function. // Ideally more and more of the format string would be parsed out here into settings until there is no remainder string // at all. // Features that this supports: // - Time formats are detected, and marked in the options. Time format strings are handled when doing the formatting. // The logic to detect time formats is currently not correct, and can catch formats that are not time formats as well // as miss formats that are time formats. // - Color formats are detected and removed. // - Currency annotations are handled properly. // - Literal strings wrapped in quotes are handled and put into prefix or suffix. // - Numbers that should be percent are detected and marked in the options. // - Conditionals are detected and removed, but they are not obeyed. The conditional groups will be used just like the // positive;negative;zero;string format groups. Here is an example of a conditional format: "[Red][<=100];[Blue][>100]" // Decoding the actual number formatting portion is out of scope, that is placed into reducedFormatString and is used // when formatting the string. The string there will be reduced to only the things in the formattingCharacters array. // Everything not in that array has been parsed out and put into formatOptions. func parseNumberFormatSection(fullFormat string) (*formatOptions, error)
{ reducedFormat := strings.TrimSpace(fullFormat) // general is the only format that does not use the normal format symbols notations if compareFormatString(reducedFormat, "general") { return &formatOptions{ fullFormatString: "general", reducedFormatString: "general", }, nil } prefix, reducedFormat, showPercent1, err := parseLiterals(reducedFormat) if err != nil { return nil, err } reducedFormat, suffixFormat := splitFormatAndSuffixFormat(reducedFormat) suffix, remaining, showPercent2, err := parseLiterals(suffixFormat) if err != nil { return nil, err } if len(remaining) > 0 { // This paradigm of codes consisting of literals, number formats, then more literals is not always correct, they can // actually be intertwined. Though 99% of the time number formats will not do this. // Excel uses this format string for Social Security Numbers: 000\-00\-0000 // and this for US phone numbers: [<=9999999]###\-####;\(###\)\ ###\-#### return nil, errors.New("invalid or unsupported format string") } return &formatOptions{ fullFormatString: fullFormat, isTimeFormat: false, reducedFormatString: reducedFormat, prefix: prefix, suffix: suffix, showPercent: showPercent1 || showPercent2, }, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
format_code.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L508-L568
go
train
// parseTime returns a string parsed using time.Time
func (fullFormat *parsedNumberFormat) parseTime(value string, date1904 bool) (string, error)
// parseTime returns a string parsed using time.Time func (fullFormat *parsedNumberFormat) parseTime(value string, date1904 bool) (string, error)
{ f, err := strconv.ParseFloat(value, 64) if err != nil { return value, err } val := TimeFromExcelTime(f, date1904) format := fullFormat.numFmt // Replace Excel placeholders with Go time placeholders. // For example, replace yyyy with 2006. These are in a specific order, // due to the fact that m is used in month, minute, and am/pm. It would // be easier to fix that with regular expressions, but if it's possible // to keep this simple it would be easier to maintain. // Full-length month and days (e.g. March, Tuesday) have letters in them that would be replaced // by other characters below (such as the 'h' in March, or the 'd' in Tuesday) below. // First we convert them to arbitrary characters unused in Excel Date formats, and then at the end, // turn them to what they should actually be. // Based off: http://www.ozgrid.com/Excel/CustomFormats.htm replacements := []struct{ xltime, gotime string }{ {"yyyy", "2006"}, {"yy", "06"}, {"mmmm", "%%%%"}, {"dddd", "&&&&"}, {"dd", "02"}, {"d", "2"}, {"mmm", "Jan"}, {"mmss", "0405"}, {"ss", "05"}, {"mm:", "04:"}, {":mm", ":04"}, {"mm", "01"}, {"am/pm", "pm"}, {"m/", "1/"}, {"%%%%", "January"}, {"&&&&", "Monday"}, } // It is the presence of the "am/pm" indicator that determins // if this is a 12 hour or 24 hours time format, not the // number of 'h' characters. if is12HourTime(format) { format = strings.Replace(format, "hh", "03", 1) format = strings.Replace(format, "h", "3", 1) } else { format = strings.Replace(format, "hh", "15", 1) format = strings.Replace(format, "h", "15", 1) } for _, repl := range replacements { format = strings.Replace(format, repl.xltime, repl.gotime, 1) } // If the hour is optional, strip it out, along with the // possible dangling colon that would remain. if val.Hour() < 1 { format = strings.Replace(format, "]:", "]", 1) format = strings.Replace(format, "[03]", "", 1) format = strings.Replace(format, "[3]", "", 1) format = strings.Replace(format, "[15]", "", 1) } else { format = strings.Replace(format, "[3]", "3", 1) format = strings.Replace(format, "[15]", "15", 1) } return val.Format(format), nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
format_code.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/format_code.go#L572-L638
go
train
// isTimeFormat checks whether an Excel format string represents a time.Time. // This function is now correct, but it can detect time format strings that cannot be correctly handled by parseTime()
func isTimeFormat(format string) bool
// isTimeFormat checks whether an Excel format string represents a time.Time. // This function is now correct, but it can detect time format strings that cannot be correctly handled by parseTime() func isTimeFormat(format string) bool
{ var foundTimeFormatCharacters bool for i := 0; i < len(format); i++ { curReducedFormat := format[i:] switch curReducedFormat[0] { case '\\', '_': // If there is a slash, skip the next character, and add it to the prefix // If there is an underscore, skip the next character, but don't add it to the prefix if len(curReducedFormat) > 1 { i++ } case '*': // Asterisks are used to repeat the next character to fill the full cell width. // There isn't really a cell size in this context, so this will be ignored. case '"': // If there is a quote skip to the next quote, and add the quoted characters to the prefix endQuoteIndex := strings.Index(curReducedFormat[1:], "\"") if endQuoteIndex == -1 { // This is not any type of valid format. return false } i += endQuoteIndex + 1 case '$', '-', '+', '/', '(', ')', ':', '!', '^', '&', '\'', '~', '{', '}', '<', '>', '=', ' ': // These symbols are allowed to be used as literal without escaping case ',': // This is not documented in the XLSX spec as far as I can tell, but Excel and Numbers will include // commas in number formats without escaping them, so this should be supported. default: foundInThisLoop := false for _, special := range timeFormatCharacters { if strings.HasPrefix(curReducedFormat, special) { foundTimeFormatCharacters = true foundInThisLoop = true i += len(special) - 1 break } } if foundInThisLoop { continue } if curReducedFormat[0] == '[' { // For number formats, this code would happen above in a case '[': section. // However, for time formats it must happen after looking for occurrences in timeFormatCharacters // because there are a few time formats that can be wrapped in brackets. // Brackets can be currency annotations (e.g. [$$-409]) // color formats (e.g. [color1] through [color56], as well as [red] etc.) // conditionals (e.g. [>100], the valid conditionals are =, >, <, >=, <=, <>) bracketIndex := strings.Index(curReducedFormat, "]") if bracketIndex == -1 { // This is not any type of valid format. return false } i += bracketIndex continue } // Symbols that don't have meaning, aren't in the exempt literal characters, and aren't escaped are invalid. // The string could still be a valid number format string. return false } } // If the string doesn't have any time formatting characters, it could technically be a time format, but it // would be a pretty weak time format. A valid time format with no time formatting symbols will also be a number // format with no number formatting symbols, which is essentially a constant string that does not depend on the // cell's value in anyway. The downstream logic will do the right thing in that case if this returns false. return foundTimeFormatCharacters }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
data_validation.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/data_validation.go#L72-L87
go
train
// SetError set error notice
func (dd *xlsxCellDataValidation) SetError(style DataValidationErrorStyle, title, msg *string)
// SetError set error notice func (dd *xlsxCellDataValidation) SetError(style DataValidationErrorStyle, title, msg *string)
{ dd.ShowErrorMessage = true dd.Error = msg dd.ErrorTitle = title strStyle := styleStop switch style { case StyleStop: strStyle = styleStop case StyleWarning: strStyle = styleWarning case StyleInformation: strStyle = styleInformation } dd.ErrorStyle = &strStyle }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
data_validation.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/data_validation.go#L114-L128
go
train
// SetInFileList is like SetDropList, excel that instead of having a hard coded list, // a reference to a part of the file is accepted and the list is automatically taken from there. // Setting y2 to -1 will select all the way to the end of the column. Selecting to the end of the // column will cause Google Sheets to spin indefinitely while trying to load the possible drop down // values (more than 5 minutes). // List validations do not work in Apple Numbers.
func (dd *xlsxCellDataValidation) SetInFileList(sheet string, x1, y1, x2, y2 int) error
// SetInFileList is like SetDropList, excel that instead of having a hard coded list, // a reference to a part of the file is accepted and the list is automatically taken from there. // Setting y2 to -1 will select all the way to the end of the column. Selecting to the end of the // column will cause Google Sheets to spin indefinitely while trying to load the possible drop down // values (more than 5 minutes). // List validations do not work in Apple Numbers. func (dd *xlsxCellDataValidation) SetInFileList(sheet string, x1, y1, x2, y2 int) error
{ start := GetCellIDStringFromCoordsWithFixed(x1, y1, true, true) if y2 < 0 { y2 = Excel2006MaxRowIndex } end := GetCellIDStringFromCoordsWithFixed(x2, y2, true, true) // Escape single quotes in the file name. // Single quotes are escaped by replacing them with two single quotes. sheet = strings.Replace(sheet, "'", "''", -1) formula := "'" + sheet + "'" + externalSheetBangChar + start + cellRangeChar + end dd.Formula1 = formula dd.Type = convDataValidationType(dataValidationTypeList) return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
data_validation.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/data_validation.go#L131-L155
go
train
// SetDropList data validation range
func (dd *xlsxCellDataValidation) SetRange(f1, f2 int, t DataValidationType, o DataValidationOperator) error
// SetDropList data validation range func (dd *xlsxCellDataValidation) SetRange(f1, f2 int, t DataValidationType, o DataValidationOperator) error
{ formula1 := fmt.Sprintf("%d", f1) formula2 := fmt.Sprintf("%d", f2) switch o { case DataValidationOperatorBetween: if f1 > f2 { tmp := formula1 formula1 = formula2 formula2 = tmp } case DataValidationOperatorNotBetween: if f1 > f2 { tmp := formula1 formula1 = formula2 formula2 = tmp } } dd.Formula1 = formula1 dd.Formula2 = formula2 dd.Type = convDataValidationType(t) dd.Operator = convDataValidationOperatior(o) return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
style.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/style.go#L20-L27
go
train
// Return a new Style structure initialised with the default values.
func NewStyle() *Style
// Return a new Style structure initialised with the default values. func NewStyle() *Style
{ return &Style{ Alignment: *DefaultAlignment(), Border: *DefaultBorder(), Fill: *DefaultFill(), Font: *DefaultFont(), } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
style.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/style.go#L30-L85
go
train
// Generate the underlying XLSX style elements that correspond to the Style.
func (style *Style) makeXLSXStyleElements() (xFont xlsxFont, xFill xlsxFill, xBorder xlsxBorder, xCellXf xlsxXf)
// Generate the underlying XLSX style elements that correspond to the Style. func (style *Style) makeXLSXStyleElements() (xFont xlsxFont, xFill xlsxFill, xBorder xlsxBorder, xCellXf xlsxXf)
{ xFont = xlsxFont{} xFill = xlsxFill{} xBorder = xlsxBorder{} xCellXf = xlsxXf{} xFont.Sz.Val = strconv.Itoa(style.Font.Size) xFont.Name.Val = style.Font.Name xFont.Family.Val = strconv.Itoa(style.Font.Family) xFont.Charset.Val = strconv.Itoa(style.Font.Charset) xFont.Color.RGB = style.Font.Color if style.Font.Bold { xFont.B = &xlsxVal{} } else { xFont.B = nil } if style.Font.Italic { xFont.I = &xlsxVal{} } else { xFont.I = nil } if style.Font.Underline { xFont.U = &xlsxVal{} } else { xFont.U = nil } xPatternFill := xlsxPatternFill{} xPatternFill.PatternType = style.Fill.PatternType xPatternFill.FgColor.RGB = style.Fill.FgColor xPatternFill.BgColor.RGB = style.Fill.BgColor xFill.PatternFill = xPatternFill xBorder.Left = xlsxLine{ Style: style.Border.Left, Color: xlsxColor{RGB: style.Border.LeftColor}, } xBorder.Right = xlsxLine{ Style: style.Border.Right, Color: xlsxColor{RGB: style.Border.RightColor}, } xBorder.Top = xlsxLine{ Style: style.Border.Top, Color: xlsxColor{RGB: style.Border.TopColor}, } xBorder.Bottom = xlsxLine{ Style: style.Border.Bottom, Color: xlsxColor{RGB: style.Border.BottomColor}, } xCellXf = makeXLSXCellElement() xCellXf.ApplyBorder = style.ApplyBorder xCellXf.ApplyFill = style.ApplyFill xCellXf.ApplyFont = style.ApplyFont xCellXf.ApplyAlignment = style.ApplyAlignment if style.NamedStyleIndex != nil { xCellXf.XfId = style.NamedStyleIndex } return }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L147-L150
go
train
// ColIndexToLetters is used to convert a zero based, numeric column // indentifier into a character code.
func ColIndexToLetters(colRef int) string
// ColIndexToLetters is used to convert a zero based, numeric column // indentifier into a character code. func ColIndexToLetters(colRef int) string
{ parts := intToBase26(colRef) return formatColumnName(smooshBase26Slice(parts)) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L182-L191
go
train
// GetCoordsFromCellIDString returns the zero based cartesian // coordinates from a cell name in Excel format, e.g. the cellIDString // "A1" returns 0, 0 and the "B3" return 1, 2.
func GetCoordsFromCellIDString(cellIDString string) (x, y int, error error)
// GetCoordsFromCellIDString returns the zero based cartesian // coordinates from a cell name in Excel format, e.g. the cellIDString // "A1" returns 0, 0 and the "B3" return 1, 2. func GetCoordsFromCellIDString(cellIDString string) (x, y int, error error)
{ var letterPart string = strings.Map(letterOnlyMapF, cellIDString) y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString)) if error != nil { return x, y, error } y -= 1 // Zero based x = ColLettersToIndex(letterPart) return x, y, error }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L195-L197
go
train
// GetCellIDStringFromCoords returns the Excel format cell name that // represents a pair of zero based cartesian coordinates.
func GetCellIDStringFromCoords(x, y int) string
// GetCellIDStringFromCoords returns the Excel format cell name that // represents a pair of zero based cartesian coordinates. func GetCellIDStringFromCoords(x, y int) string
{ return GetCellIDStringFromCoordsWithFixed(x, y, false, false) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L202-L212
go
train
// GetCellIDStringFromCoordsWithFixed returns the Excel format cell name that // represents a pair of zero based cartesian coordinates. // It can specify either value as fixed.
func GetCellIDStringFromCoordsWithFixed(x, y int, xFixed, yFixed bool) string
// GetCellIDStringFromCoordsWithFixed returns the Excel format cell name that // represents a pair of zero based cartesian coordinates. // It can specify either value as fixed. func GetCellIDStringFromCoordsWithFixed(x, y int, xFixed, yFixed bool) string
{ xStr := ColIndexToLetters(x) if xFixed { xStr = fixedCellRefChar + xStr } yStr := RowIndexToString(y) if yFixed { yStr = fixedCellRefChar + yStr } return xStr + yStr }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L218-L230
go
train
// getMaxMinFromDimensionRef return the zero based cartesian maximum // and minimum coordinates from the dimension reference embedded in a // XLSX worksheet. For example, the dimension reference "A1:B2" // returns "0,0", "1,1".
func getMaxMinFromDimensionRef(ref string) (minx, miny, maxx, maxy int, err error)
// getMaxMinFromDimensionRef return the zero based cartesian maximum // and minimum coordinates from the dimension reference embedded in a // XLSX worksheet. For example, the dimension reference "A1:B2" // returns "0,0", "1,1". func getMaxMinFromDimensionRef(ref string) (minx, miny, maxx, maxy int, err error)
{ var parts []string parts = strings.Split(ref, cellRangeChar) minx, miny, err = GetCoordsFromCellIDString(parts[0]) if err != nil { return -1, -1, -1, -1, err } maxx, maxy, err = GetCoordsFromCellIDString(parts[1]) if err != nil { return -1, -1, -1, -1, err } return }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L236-L272
go
train
// calculateMaxMinFromWorkSheet works out the dimensions of a spreadsheet // that doesn't have a DimensionRef set. The only case currently // known where this is true is with XLSX exported from Google Docs. // This is also true for XLSX files created through the streaming APIs.
func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error)
// calculateMaxMinFromWorkSheet works out the dimensions of a spreadsheet // that doesn't have a DimensionRef set. The only case currently // known where this is true is with XLSX exported from Google Docs. // This is also true for XLSX files created through the streaming APIs. func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error)
{ // Note, this method could be very slow for large spreadsheets. var x, y int var maxVal int maxVal = int(^uint(0) >> 1) minx = maxVal miny = maxVal maxy = 0 maxx = 0 for _, row := range worksheet.SheetData.Row { for _, cell := range row.C { x, y, err = GetCoordsFromCellIDString(cell.R) if err != nil { return -1, -1, -1, -1, err } if x < minx { minx = x } if x > maxx { maxx = x } if y < miny { miny = y } if y > maxy { maxy = y } } } if minx == maxVal { minx = 0 } if miny == maxVal { miny = 0 } return }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L301-L334
go
train
// makeRowFromRaw returns the Row representation of the xlsxRow.
func makeRowFromRaw(rawrow xlsxRow, sheet *Sheet) *Row
// makeRowFromRaw returns the Row representation of the xlsxRow. func makeRowFromRaw(rawrow xlsxRow, sheet *Sheet) *Row
{ var upper int var row *Row var cell *Cell row = new(Row) row.Sheet = sheet upper = -1 for _, rawcell := range rawrow.C { if rawcell.R != "" { x, _, error := GetCoordsFromCellIDString(rawcell.R) if error != nil { panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R)) } if x > upper { upper = x } continue } upper++ } upper++ row.OutlineLevel = rawrow.OutlineLevel row.Cells = make([]*Cell, upper) for i := 0; i < upper; i++ { cell = new(Cell) cell.Value = "" row.Cells[i] = cell } return row }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L418-L463
go
train
// shiftCell returns the cell shifted according to dx and dy taking into consideration of absolute // references with dollar sign ($)
func shiftCell(cellID string, dx, dy int) string
// shiftCell returns the cell shifted according to dx and dy taking into consideration of absolute // references with dollar sign ($) func shiftCell(cellID string, dx, dy int) string
{ fx, fy, _ := GetCoordsFromCellIDString(cellID) // Is fixed column? fixedCol := strings.Index(cellID, fixedCellRefChar) == 0 // Is fixed row? fixedRow := strings.LastIndex(cellID, fixedCellRefChar) > 0 if !fixedCol { // Shift column fx += dx } if !fixedRow { // Shift row fy += dy } // New shifted cell shiftedCellID := GetCellIDStringFromCoords(fx, fy) if !fixedCol && !fixedRow { return shiftedCellID } // There are absolute references, need to put the $ back into the formula. letterPart := strings.Map(letterOnlyMapF, shiftedCellID) numberPart := strings.Map(intOnlyMapF, shiftedCellID) result := "" if fixedCol { result += "$" } result += letterPart if fixedRow { result += "$" } result += numberPart return result }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L468-L506
go
train
// fillCellData attempts to extract a valid value, usable in // CSV form from the raw cell value. Note - this is not actually // general enough - we should support retaining tabs and newlines.
func fillCellData(rawCell xlsxC, refTable *RefTable, sharedFormulas map[int]sharedFormula, cell *Cell)
// fillCellData attempts to extract a valid value, usable in // CSV form from the raw cell value. Note - this is not actually // general enough - we should support retaining tabs and newlines. func fillCellData(rawCell xlsxC, refTable *RefTable, sharedFormulas map[int]sharedFormula, cell *Cell)
{ val := strings.Trim(rawCell.V, " \t\n\r") cell.formula = formulaForCell(rawCell, sharedFormulas) switch rawCell.T { case "s": // Shared String cell.cellType = CellTypeString if val != "" { ref, err := strconv.Atoi(val) if err != nil { panic(err) } cell.Value = refTable.ResolveSharedString(ref) } case "inlineStr": cell.cellType = CellTypeInline fillCellDataFromInlineString(rawCell, cell) case "b": // Boolean cell.Value = val cell.cellType = CellTypeBool case "e": // Error cell.Value = val cell.cellType = CellTypeError case "str": // String Formula (special type for cells with formulas that return a string value) // Unlike the other string cell types, the string is stored directly in the value. cell.Value = val cell.cellType = CellTypeStringFormula case "d": // Date: Cell contains a date in the ISO 8601 format. cell.Value = val cell.cellType = CellTypeDate case "": // Numeric is the default fallthrough case "n": // Numeric cell.Value = val cell.cellType = CellTypeNumeric default: panic(errors.New("invalid cell type")) } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L509-L520
go
train
// fillCellDataFromInlineString attempts to get inline string data and put it into a Cell.
func fillCellDataFromInlineString(rawcell xlsxC, cell *Cell)
// fillCellDataFromInlineString attempts to get inline string data and put it into a Cell. func fillCellDataFromInlineString(rawcell xlsxC, cell *Cell)
{ cell.Value = "" if rawcell.Is != nil { if rawcell.Is.T != "" { cell.Value = strings.Trim(rawcell.Is.T, " \t\n\r") } else { for _, r := range rawcell.Is.R { cell.Value += r.T } } } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L526-L658
go
train
// readRowsFromSheet is an internal helper function that extracts the // rows from a XSLXWorksheet, populates them with Cells and resolves // the value references from the reference table and stores them in // the rows and columns.
func readRowsFromSheet(Worksheet *xlsxWorksheet, file *File, sheet *Sheet, rowLimit int) ([]*Row, []*Col, int, int)
// readRowsFromSheet is an internal helper function that extracts the // rows from a XSLXWorksheet, populates them with Cells and resolves // the value references from the reference table and stores them in // the rows and columns. func readRowsFromSheet(Worksheet *xlsxWorksheet, file *File, sheet *Sheet, rowLimit int) ([]*Row, []*Col, int, int)
{ var rows []*Row var cols []*Col var row *Row var minCol, maxCol, maxRow, colCount, rowCount int var reftable *RefTable var err error var insertRowIndex, insertColIndex int sharedFormulas := map[int]sharedFormula{} if len(Worksheet.SheetData.Row) == 0 { return nil, nil, 0, 0 } reftable = file.referenceTable if len(Worksheet.Dimension.Ref) > 0 && len(strings.Split(Worksheet.Dimension.Ref, cellRangeChar)) == 2 && rowLimit == NoRowLimit { minCol, _, maxCol, maxRow, err = getMaxMinFromDimensionRef(Worksheet.Dimension.Ref) } else { minCol, _, maxCol, maxRow, err = calculateMaxMinFromWorksheet(Worksheet) } if err != nil { panic(err.Error()) } rowCount = maxRow + 1 colCount = maxCol + 1 rows = make([]*Row, rowCount) cols = make([]*Col, colCount) for i := range cols { cols[i] = &Col{ Hidden: false, } } if Worksheet.Cols != nil { // Columns can apply to a range, for convenience we expand the // ranges out into individual column definitions. for _, rawcol := range Worksheet.Cols.Col { // Note, below, that sometimes column definitions can // exist outside the defined dimensions of the // spreadsheet - we deliberately exclude these // columns. for i := rawcol.Min; i <= rawcol.Max && i <= colCount; i++ { col := &Col{ Min: rawcol.Min, Max: rawcol.Max, Hidden: rawcol.Hidden, Width: rawcol.Width, OutlineLevel: rawcol.OutlineLevel} cols[i-1] = col if file.styles != nil { col.style = file.styles.getStyle(rawcol.Style) col.numFmt, col.parsedNumFmt = file.styles.getNumberFormat(rawcol.Style) } } } } numRows := len(rows) for rowIndex := 0; rowIndex < len(Worksheet.SheetData.Row); rowIndex++ { rawrow := Worksheet.SheetData.Row[rowIndex] // Some spreadsheets will omit blank rows from the // stored data for rawrow.R > (insertRowIndex + 1) { // Put an empty Row into the array if insertRowIndex < numRows { rows[insertRowIndex] = makeEmptyRow(sheet) } insertRowIndex++ } // range is not empty and only one range exist if len(rawrow.Spans) != 0 && strings.Count(rawrow.Spans, cellRangeChar) == 1 { row = makeRowFromSpan(rawrow.Spans, sheet) } else { row = makeRowFromRaw(rawrow, sheet) } row.Hidden = rawrow.Hidden height, err := strconv.ParseFloat(rawrow.Ht, 64) if err == nil { row.Height = height } row.isCustom = rawrow.CustomHeight row.OutlineLevel = rawrow.OutlineLevel insertColIndex = minCol for _, rawcell := range rawrow.C { h, v, err := Worksheet.MergeCells.getExtent(rawcell.R) if err != nil { panic(err.Error()) } x, _, _ := GetCoordsFromCellIDString(rawcell.R) // K1000000: Prevent panic when the range specified in the spreadsheet // view exceeds the actual number of columns in the dataset. // Some spreadsheets will omit blank cells // from the data. for x > insertColIndex { // Put an empty Cell into the array if insertColIndex < len(row.Cells) { row.Cells[insertColIndex] = new(Cell) } insertColIndex++ } cellX := insertColIndex if cellX < len(row.Cells) { cell := row.Cells[cellX] cell.HMerge = h cell.VMerge = v fillCellData(rawcell, reftable, sharedFormulas, cell) if file.styles != nil { cell.style = file.styles.getStyle(rawcell.S) cell.NumFmt, cell.parsedNumFmt = file.styles.getNumberFormat(rawcell.S) } cell.date1904 = file.Date1904 // Cell is considered hidden if the row or the column of this cell is hidden cell.Hidden = rawrow.Hidden || (len(cols) > cellX && cols[cellX].Hidden) insertColIndex++ } } if len(rows) > insertRowIndex { rows[insertRowIndex] = row } insertRowIndex++ } // insert trailing empty rows for the rest of the file for ; insertRowIndex < rowCount; insertRowIndex++ { rows[insertRowIndex] = makeEmptyRow(sheet) } return rows, cols, colCount, rowCount }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L692-L772
go
train
// readSheetFromFile is the logic of converting a xlsxSheet struct // into a Sheet struct. This work can be done in parallel and so // readSheetsFromZipFile will spawn an instance of this function per // sheet and get the results back on the provided channel.
func readSheetFromFile(sc chan *indexedSheet, index int, rsheet xlsxSheet, fi *File, sheetXMLMap map[string]string, rowLimit int) (errRes error)
// readSheetFromFile is the logic of converting a xlsxSheet struct // into a Sheet struct. This work can be done in parallel and so // readSheetsFromZipFile will spawn an instance of this function per // sheet and get the results back on the provided channel. func readSheetFromFile(sc chan *indexedSheet, index int, rsheet xlsxSheet, fi *File, sheetXMLMap map[string]string, rowLimit int) (errRes error)
{ result := &indexedSheet{Index: index, Sheet: nil, Error: nil} defer func() { if e := recover(); e != nil { switch e.(type) { case error: result.Error = e.(error) errRes = e.(error) default: result.Error = errors.New("unexpected error") } // The only thing here, is if one close the channel. but its not the case sc <- result } }() worksheet, err := getWorksheetFromSheet(rsheet, fi.worksheets, sheetXMLMap, rowLimit) if err != nil { result.Error = err sc <- result return err } sheet := new(Sheet) sheet.File = fi sheet.Rows, sheet.Cols, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, fi, sheet, rowLimit) sheet.Hidden = rsheet.State == sheetStateHidden || rsheet.State == sheetStateVeryHidden sheet.SheetViews = readSheetViews(worksheet.SheetViews) sheet.SheetFormat.DefaultColWidth = worksheet.SheetFormatPr.DefaultColWidth sheet.SheetFormat.DefaultRowHeight = worksheet.SheetFormatPr.DefaultRowHeight sheet.SheetFormat.OutlineLevelCol = worksheet.SheetFormatPr.OutlineLevelCol sheet.SheetFormat.OutlineLevelRow = worksheet.SheetFormatPr.OutlineLevelRow if nil != worksheet.DataValidations { for _, dd := range worksheet.DataValidations.DataValidation { sqrefArr := strings.Split(dd.Sqref, " ") for _, sqref := range sqrefArr { parts := strings.Split(sqref, cellRangeChar) minCol, minRow, err := GetCoordsFromCellIDString(parts[0]) if nil != err { return fmt.Errorf("data validation %s", err.Error()) } if 2 == len(parts) { maxCol, maxRow, err := GetCoordsFromCellIDString(parts[1]) if nil != err { return fmt.Errorf("data validation %s", err.Error()) } if minCol == maxCol && minRow == maxRow { newDD := new(xlsxCellDataValidation) *newDD = *dd newDD.Sqref = "" sheet.Cell(minRow, minCol).SetDataValidation(newDD) } else { // one col mutli dd , error todo for i := minCol; i <= maxCol; i++ { newDD := new(xlsxCellDataValidation) *newDD = *dd newDD.Sqref = "" sheet.Col(i).SetDataValidation(dd, minRow, maxRow) } } } else { newDD := new(xlsxCellDataValidation) *newDD = *dd newDD.Sqref = "" sheet.Cell(minRow, minCol).SetDataValidation(dd) } } } } result.Sheet = sheet sc <- result return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L777-L833
go
train
// readSheetsFromZipFile is an internal helper function that loops // over the Worksheets defined in the XSLXWorkbook and loads them into // Sheet objects stored in the Sheets slice of a xlsx.File struct.
func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string, rowLimit int) (map[string]*Sheet, []*Sheet, error)
// readSheetsFromZipFile is an internal helper function that loops // over the Worksheets defined in the XSLXWorkbook and loads them into // Sheet objects stored in the Sheets slice of a xlsx.File struct. func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string, rowLimit int) (map[string]*Sheet, []*Sheet, error)
{ var workbook *xlsxWorkbook var err error var rc io.ReadCloser var decoder *xml.Decoder var sheetCount int workbook = new(xlsxWorkbook) rc, err = f.Open() if err != nil { return nil, nil, err } decoder = xml.NewDecoder(rc) err = decoder.Decode(workbook) if err != nil { return nil, nil, err } file.Date1904 = workbook.WorkbookPr.Date1904 for entryNum := range workbook.DefinedNames.DefinedName { file.DefinedNames = append(file.DefinedNames, &workbook.DefinedNames.DefinedName[entryNum]) } // Only try and read sheets that have corresponding files. // Notably this excludes chartsheets don't right now var workbookSheets []xlsxSheet for _, sheet := range workbook.Sheets.Sheet { if f := worksheetFileForSheet(sheet, file.worksheets, sheetXMLMap); f != nil { workbookSheets = append(workbookSheets, sheet) } } sheetCount = len(workbookSheets) sheetsByName := make(map[string]*Sheet, sheetCount) sheets := make([]*Sheet, sheetCount) sheetChan := make(chan *indexedSheet, sheetCount) go func() { defer close(sheetChan) err = nil for i, rawsheet := range workbookSheets { if err := readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap, rowLimit); err != nil { return } } }() for j := 0; j < sheetCount; j++ { sheet := <-sheetChan if sheet.Error != nil { return nil, nil, sheet.Error } sheetName := workbookSheets[sheet.Index].Name sheetsByName[sheetName] = sheet.Sheet sheet.Sheet.Name = sheetName sheets[sheet.Index] = sheet.Sheet } return sheetsByName, sheets, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L991-L994
go
train
// ReadZipWithRowLimit() takes a pointer to a zip.ReadCloser and returns a // xlsx.File struct populated with its contents. In most cases // ReadZip is not used directly, but is called internally by OpenFile.
func ReadZipWithRowLimit(f *zip.ReadCloser, rowLimit int) (*File, error)
// ReadZipWithRowLimit() takes a pointer to a zip.ReadCloser and returns a // xlsx.File struct populated with its contents. In most cases // ReadZip is not used directly, but is called internally by OpenFile. func ReadZipWithRowLimit(f *zip.ReadCloser, rowLimit int) (*File, error)
{ defer f.Close() return ReadZipReaderWithRowLimit(&f.Reader, rowLimit) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L1006-L1089
go
train
// ReadZipReaderWithRowLimit() can be used to read an XLSX in memory without // touching the filesystem. // rowLimit is the number of rows that should be read from the file. If rowLimit is -1, no limit is applied. // You can specify this with the constant NoRowLimit.
func ReadZipReaderWithRowLimit(r *zip.Reader, rowLimit int) (*File, error)
// ReadZipReaderWithRowLimit() can be used to read an XLSX in memory without // touching the filesystem. // rowLimit is the number of rows that should be read from the file. If rowLimit is -1, no limit is applied. // You can specify this with the constant NoRowLimit. func ReadZipReaderWithRowLimit(r *zip.Reader, rowLimit int) (*File, error)
{ var err error var file *File var reftable *RefTable var sharedStrings *zip.File var sheetXMLMap map[string]string var sheetsByName map[string]*Sheet var sheets []*Sheet var style *xlsxStyleSheet var styles *zip.File var themeFile *zip.File var v *zip.File var workbook *zip.File var workbookRels *zip.File var worksheets map[string]*zip.File file = NewFile() // file.numFmtRefTable = make(map[int]xlsxNumFmt, 1) worksheets = make(map[string]*zip.File, len(r.File)) for _, v = range r.File { switch v.Name { case "xl/sharedStrings.xml": sharedStrings = v case "xl/workbook.xml": workbook = v case "xl/_rels/workbook.xml.rels": workbookRels = v case "xl/styles.xml": styles = v case "xl/theme/theme1.xml": themeFile = v default: if len(v.Name) > 17 { if v.Name[0:13] == "xl/worksheets" { worksheets[v.Name[14:len(v.Name)-4]] = v } } } } if workbookRels == nil { return nil, fmt.Errorf("xl/_rels/workbook.xml.rels not found in input xlsx.") } sheetXMLMap, err = readWorkbookRelationsFromZipFile(workbookRels) if err != nil { return nil, err } if len(worksheets) == 0 { return nil, fmt.Errorf("Input xlsx contains no worksheets.") } file.worksheets = worksheets reftable, err = readSharedStringsFromZipFile(sharedStrings) if err != nil { return nil, err } file.referenceTable = reftable if themeFile != nil { theme, err := readThemeFromZipFile(themeFile) if err != nil { return nil, err } file.theme = theme } if styles != nil { style, err = readStylesFromZipFile(styles, file.theme) if err != nil { return nil, err } file.styles = style } sheetsByName, sheets, err = readSheetsFromZipFile(workbook, file, sheetXMLMap, rowLimit) if err != nil { return nil, err } if sheets == nil { readerErr := new(XLSXReaderError) readerErr.Err = "No sheets found in XLSX File" return nil, readerErr } file.Sheet = sheetsByName file.Sheets = sheets return file, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
lib.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/lib.go#L1096-L1131
go
train
// truncateSheetXML will take in a reader to an XML sheet file and will return a reader that will read an equivalent // XML sheet file with only the number of rows specified. This greatly speeds up XML unmarshalling when only // a few rows need to be read from a large sheet. // When sheets are truncated, all formatting present after the sheetData tag will be lost, but all of this formatting // is related to printing and visibility, and is out of scope for most purposes of this library.
func truncateSheetXML(r io.Reader, rowLimit int) (io.Reader, error)
// truncateSheetXML will take in a reader to an XML sheet file and will return a reader that will read an equivalent // XML sheet file with only the number of rows specified. This greatly speeds up XML unmarshalling when only // a few rows need to be read from a large sheet. // When sheets are truncated, all formatting present after the sheetData tag will be lost, but all of this formatting // is related to printing and visibility, and is out of scope for most purposes of this library. func truncateSheetXML(r io.Reader, rowLimit int) (io.Reader, error)
{ var rowCount int var token xml.Token var readErr error output := new(bytes.Buffer) r = io.TeeReader(r, output) decoder := xml.NewDecoder(r) for { token, readErr = decoder.Token() if readErr == io.EOF { break } else if readErr != nil { return nil, readErr } end, ok := token.(xml.EndElement) if ok && end.Name.Local == "row" { rowCount++ if rowCount >= rowLimit { break } } } offset := decoder.InputOffset() output.Truncate(int(offset)) if readErr != io.EOF { _, err := output.Write([]byte(sheetEnding)) if err != nil { return nil, err } } return output, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
write.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/write.go#L14-L85
go
train
// 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.
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. func (r *Row) WriteSlice(e interface{}, cols int) int
{ if cols == 0 { return cols } // make sure 'e' is a Ptr to Slice v := reflect.ValueOf(e) if v.Kind() != reflect.Ptr { return -1 } v = v.Elem() if v.Kind() != reflect.Slice { return -1 } // it's a slice, so open up its values n := v.Len() if cols < n && cols > 0 { n = cols } var setCell func(reflect.Value) setCell = func(val reflect.Value) { switch t := val.Interface().(type) { case time.Time: cell := r.AddCell() cell.SetValue(t) case fmt.Stringer: // check Stringer first cell := r.AddCell() cell.SetString(t.String()) case sql.NullString: // check null sql types nulls = '' cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetValue(t.String) } case sql.NullBool: cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetBool(t.Bool) } case sql.NullInt64: cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetValue(t.Int64) } case sql.NullFloat64: cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetValue(t.Float64) } default: switch val.Kind() { // underlying type of slice case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float64, reflect.Float32: cell := r.AddCell() cell.SetValue(val.Interface()) case reflect.Bool: cell := r.AddCell() cell.SetBool(t.(bool)) case reflect.Interface: setCell(reflect.ValueOf(t)) } } } var i int for i = 0; i < n; i++ { setCell(v.Index(i)) } return i }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
write.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/write.go#L91-L153
go
train
// 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
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 func (r *Row) WriteStruct(e interface{}, cols int) int
{ if cols == 0 { return cols } v := reflect.ValueOf(e).Elem() if v.Kind() != reflect.Struct { return -1 // bail if it's not a struct } n := v.NumField() // number of fields in struct if cols < n && cols > 0 { n = cols } var k int for i := 0; i < n; i, k = i+1, k+1 { f := v.Field(i) switch t := f.Interface().(type) { case time.Time: cell := r.AddCell() cell.SetValue(t) case fmt.Stringer: // check Stringer first cell := r.AddCell() cell.SetString(t.String()) case sql.NullString: // check null sql types nulls = '' cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetValue(t.String) } case sql.NullBool: cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetBool(t.Bool) } case sql.NullInt64: cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetValue(t.Int64) } case sql.NullFloat64: cell := r.AddCell() if cell.SetString(``); t.Valid { cell.SetValue(t.Float64) } default: switch f.Kind() { case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float64, reflect.Float32: cell := r.AddCell() cell.SetValue(f.Interface()) case reflect.Bool: cell := r.AddCell() cell.SetBool(t.(bool)) default: k-- // nothing set so reset to previous } } } return k }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L32-L38
go
train
// Create a new File
func NewFile() *File
// Create a new File func NewFile() *File
{ return &File{ Sheet: make(map[string]*Sheet), Sheets: make([]*Sheet, 0), DefinedNames: make([]*xlsxDefinedName, 0), } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L42-L44
go
train
// OpenFile() take the name of an XLSX file and returns a populated // xlsx.File struct for it.
func OpenFile(fileName string) (file *File, err error)
// OpenFile() take the name of an XLSX file and returns a populated // xlsx.File struct for it. func OpenFile(fileName string) (file *File, err error)
{ return OpenFileWithRowLimit(fileName, NoRowLimit) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L48-L55
go
train
// OpenFileWithRowLimit() will open the file, but will only read the specified number of rows. // If you save this file, it will be truncated to the number of rows specified.
func OpenFileWithRowLimit(fileName string, rowLimit int) (file *File, err error)
// OpenFileWithRowLimit() will open the file, but will only read the specified number of rows. // If you save this file, it will be truncated to the number of rows specified. func OpenFileWithRowLimit(fileName string, rowLimit int) (file *File, err error)
{ var z *zip.ReadCloser z, err = zip.OpenReader(fileName) if err != nil { return nil, err } return ReadZipWithRowLimit(z, rowLimit) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L65-L68
go
train
// OpenBinaryWithRowLimit() take bytes of an XLSX file and returns a populated // xlsx.File struct for it.
func OpenBinaryWithRowLimit(bs []byte, rowLimit int) (*File, error)
// OpenBinaryWithRowLimit() take bytes of an XLSX file and returns a populated // xlsx.File struct for it. func OpenBinaryWithRowLimit(bs []byte, rowLimit int) (*File, error)
{ r := bytes.NewReader(bs) return OpenReaderAtWithRowLimit(r, int64(r.Len()), rowLimit) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L72-L74
go
train
// OpenReaderAt() take io.ReaderAt of an XLSX file and returns a populated // xlsx.File struct for it.
func OpenReaderAt(r io.ReaderAt, size int64) (*File, error)
// OpenReaderAt() take io.ReaderAt of an XLSX file and returns a populated // xlsx.File struct for it. func OpenReaderAt(r io.ReaderAt, size int64) (*File, error)
{ return OpenReaderAtWithRowLimit(r, size, NoRowLimit) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L78-L84
go
train
// OpenReaderAtWithRowLimit() take io.ReaderAt of an XLSX file and returns a populated // xlsx.File struct for it.
func OpenReaderAtWithRowLimit(r io.ReaderAt, size int64, rowLimit int) (*File, error)
// OpenReaderAtWithRowLimit() take io.ReaderAt of an XLSX file and returns a populated // xlsx.File struct for it. func OpenReaderAtWithRowLimit(r io.ReaderAt, size int64, rowLimit int) (*File, error)
{ file, err := zip.NewReader(r, size) if err != nil { return nil, err } return ReadZipReaderWithRowLimit(file, rowLimit) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L112-L118
go
train
// FileToSliceUnmerged is a wrapper around File.ToSliceUnmerged. // It returns the raw data contained in an Excel XLSX file as three // dimensional slice. Merged cells will be unmerged. Covered cells become the // values of theirs origins.
func FileToSliceUnmerged(path string) ([][][]string, error)
// FileToSliceUnmerged is a wrapper around File.ToSliceUnmerged. // It returns the raw data contained in an Excel XLSX file as three // dimensional slice. Merged cells will be unmerged. Covered cells become the // values of theirs origins. func FileToSliceUnmerged(path string) ([][][]string, error)
{ f, err := OpenFile(path) if err != nil { return nil, err } return f.ToSliceUnmerged() }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L156-L178
go
train
// Add a new Sheet, with the provided name, to a File. // 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: : \ / ? * [ ]
func (f *File) AddSheet(sheetName string) (*Sheet, error)
// Add a new Sheet, with the provided name, to a File. // 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: : \ / ? * [ ] func (f *File) AddSheet(sheetName string) (*Sheet, error)
{ if _, exists := f.Sheet[sheetName]; exists { return nil, fmt.Errorf("duplicate sheet name '%s'.", sheetName) } if utf8.RuneCountInString(sheetName) > 31 { return nil, fmt.Errorf("sheet name must be 31 or fewer characters long. It is currently '%d' characters long", utf8.RuneCountInString(sheetName)) } // Iterate over the runes for _, r := range sheetName { // Excel forbids : \ / ? * [ ] if r == ':' || r == '\\' || r == '/' || r == '?' || r == '*' || r == '[' || r == ']' { return nil, fmt.Errorf("sheet name must not contain any restricted characters : \\ / ? * [ ] but contains '%s'", string(r)) } } sheet := &Sheet{ Name: sheetName, File: f, Selected: len(f.Sheets) == 0, } f.Sheet[sheetName] = sheet f.Sheets = append(f.Sheets, sheet) return sheet, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L241-L334
go
train
// Construct a map of file name to XML content representing the file // in terms of the structure of an XLSX 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. func (f *File) MarshallParts() (map[string]string, error)
{ var parts map[string]string var refTable *RefTable = NewSharedStringRefTable() refTable.isWrite = true var workbookRels WorkBookRels = make(WorkBookRels) var err error var workbook xlsxWorkbook var types xlsxTypes = MakeDefaultContentTypes() marshal := func(thing interface{}) (string, error) { body, err := xml.Marshal(thing) if err != nil { return "", err } return xml.Header + string(body), nil } parts = make(map[string]string) workbook = f.makeWorkbook() sheetIndex := 1 if f.styles == nil { f.styles = newXlsxStyleSheet(f.theme) } f.styles.reset() if len(f.Sheets) == 0 { err := errors.New("Workbook must contains atleast one worksheet") return nil, err } for _, sheet := range f.Sheets { xSheet := sheet.makeXLSXSheet(refTable, f.styles) rId := fmt.Sprintf("rId%d", sheetIndex) sheetId := strconv.Itoa(sheetIndex) sheetPath := fmt.Sprintf("worksheets/sheet%d.xml", sheetIndex) partName := "xl/" + sheetPath types.Overrides = append( types.Overrides, xlsxOverride{ PartName: "/" + partName, ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"}) workbookRels[rId] = sheetPath workbook.Sheets.Sheet[sheetIndex-1] = xlsxSheet{ Name: sheet.Name, SheetId: sheetId, Id: rId, State: "visible"} parts[partName], err = marshal(xSheet) if err != nil { return parts, err } sheetIndex++ } workbookMarshal, err := marshal(workbook) if err != nil { return parts, err } workbookMarshal = replaceRelationshipsNameSpace(workbookMarshal) parts["xl/workbook.xml"] = workbookMarshal if err != nil { return parts, err } parts["_rels/.rels"] = TEMPLATE__RELS_DOT_RELS parts["docProps/app.xml"] = TEMPLATE_DOCPROPS_APP // TODO - do this properly, modification and revision information parts["docProps/core.xml"] = TEMPLATE_DOCPROPS_CORE parts["xl/theme/theme1.xml"] = TEMPLATE_XL_THEME_THEME xSST := refTable.makeXLSXSST() parts["xl/sharedStrings.xml"], err = marshal(xSST) if err != nil { return parts, err } xWRel := workbookRels.MakeXLSXWorkbookRels() parts["xl/_rels/workbook.xml.rels"], err = marshal(xWRel) if err != nil { return parts, err } parts["[Content_Types].xml"], err = marshal(types) if err != nil { return parts, err } parts["xl/styles.xml"], err = f.styles.Marshal() if err != nil { return parts, err } return parts, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L349-L376
go
train
// 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) 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) ToSlice() (output [][][]string, err error)
{ output = [][][]string{} for _, sheet := range f.Sheets { s := [][]string{} for _, row := range sheet.Rows { if row == nil { continue } r := []string{} for _, cell := range row.Cells { str, err := cell.FormattedValue() if err != nil { // Recover from strconv.NumError if the value is an empty string, // and insert an empty string in the output. if numErr, ok := err.(*strconv.NumError); ok && numErr.Num == "" { str = "" } else { return output, err } } r = append(r, str) } s = append(s, r) } output = append(output, s) } return output, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
file.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/file.go#L387-L412
go
train
// 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) 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) ToSliceUnmerged() (output [][][]string, err error)
{ output, err = f.ToSlice() if err != nil { return nil, err } for s, sheet := range f.Sheets { for r, row := range sheet.Rows { for c, cell := range row.Cells { if cell.HMerge > 0 { for i := c + 1; i <= c+cell.HMerge; i++ { output[s][r][i] = output[s][r][c] } } if cell.VMerge > 0 { for i := r + 1; i <= r+cell.VMerge; i++ { output[s][i][c] = output[s][r][c] } } } } } return output, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L60-L75
go
train
// Add a new Row to a Sheet at a specific index
func (s *Sheet) AddRowAtIndex(index int) (*Row, error)
// Add a new Row to a Sheet at a specific index func (s *Sheet) AddRowAtIndex(index int) (*Row, error)
{ if index < 0 || index > len(s.Rows) { return nil, errors.New("AddRowAtIndex: index out of bounds") } row := &Row{Sheet: s} s.Rows = append(s.Rows, nil) if index < len(s.Rows) { copy(s.Rows[index+1:], s.Rows[index:]) } s.Rows[index] = row if len(s.Rows) > s.MaxRow { s.MaxRow = len(s.Rows) } return row, nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L78-L84
go
train
// Removes a row at a specific index
func (s *Sheet) RemoveRowAtIndex(index int) error
// Removes a row at a specific index func (s *Sheet) RemoveRowAtIndex(index int) error
{ if index < 0 || index >= len(s.Rows) { return errors.New("RemoveRowAtIndex: index out of bounds") } s.Rows = append(s.Rows[:index], s.Rows[index+1:]...) return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L87-L97
go
train
// Make sure we always have as many Rows as we do cells.
func (s *Sheet) maybeAddRow(rowCount int)
// Make sure we always have as many Rows as we do cells. func (s *Sheet) maybeAddRow(rowCount int)
{ if rowCount > s.MaxRow { loopCnt := rowCount - s.MaxRow for i := 0; i < loopCnt; i++ { row := &Row{Sheet: s} s.Rows = append(s.Rows, row) } s.MaxRow = rowCount } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L100-L103
go
train
// Make sure we always have as many Rows as we do cells.
func (s *Sheet) Row(idx int) *Row
// Make sure we always have as many Rows as we do cells. func (s *Sheet) Row(idx int) *Row
{ s.maybeAddRow(idx + 1) return s.Rows[idx] }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L106-L124
go
train
// Make sure we always have as many Cols as we do cells.
func (s *Sheet) maybeAddCol(cellCount int)
// Make sure we always have as many Cols as we do cells. func (s *Sheet) maybeAddCol(cellCount int)
{ if cellCount > s.MaxCol { loopCnt := cellCount - s.MaxCol currIndex := s.MaxCol + 1 for i := 0; i < loopCnt; i++ { col := &Col{ style: NewStyle(), Min: currIndex, Max: currIndex, Hidden: false, Collapsed: false} s.Cols = append(s.Cols, col) currIndex++ } s.MaxCol = cellCount } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L141-L154
go
train
// Get a Cell by passing it's cartesian coordinates (zero based) as // row and column integer indexes. // // For example: // // cell := sheet.Cell(0,0) // // ... would set the variable "cell" to contain a Cell struct // containing the data from the field "A1" on the spreadsheet.
func (sh *Sheet) Cell(row, col int) *Cell
// Get a Cell by passing it's cartesian coordinates (zero based) as // row and column integer indexes. // // For example: // // cell := sheet.Cell(0,0) // // ... would set the variable "cell" to contain a Cell struct // containing the data from the field "A1" on the spreadsheet. func (sh *Sheet) Cell(row, col int) *Cell
{ // If the user requests a row beyond what we have, then extend. for len(sh.Rows) <= row { sh.AddRow() } r := sh.Rows[row] for len(r.Cells) <= col { r.AddCell() } return r.Cells[col] }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L157-L168
go
train
//Set the width of a single column or multiple columns.
func (s *Sheet) SetColWidth(startcol, endcol int, width float64) error
//Set the width of a single column or multiple columns. func (s *Sheet) SetColWidth(startcol, endcol int, width float64) error
{ if startcol > endcol { return fmt.Errorf("Could not set width for range %d-%d: startcol must be less than endcol.", startcol, endcol) } end := endcol + 1 s.maybeAddCol(end) for ; startcol < end; startcol++ { s.Cols[startcol].Width = width } return nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L175-L201
go
train
// When merging cells, the cell may be the 'original' or the 'covered'. // First, figure out which cells are merge starting points. Then create // the necessary cells underlying the merge area. // Then go through all the underlying cells and apply the appropriate // border, based on the original cell.
func (s *Sheet) handleMerged()
// When merging cells, the cell may be the 'original' or the 'covered'. // First, figure out which cells are merge starting points. Then create // the necessary cells underlying the merge area. // Then go through all the underlying cells and apply the appropriate // border, based on the original cell. func (s *Sheet) handleMerged()
{ merged := make(map[string]*Cell) for r, row := range s.Rows { for c, cell := range row.Cells { if cell.HMerge > 0 || cell.VMerge > 0 { coord := GetCellIDStringFromCoords(c, r) merged[coord] = cell } } } // This loop iterates over all cells that should be merged and applies the correct // borders to them depending on their position. If any cells required by the merge // are missing, they will be allocated by s.Cell(). for key, cell := range merged { maincol, mainrow, _ := GetCoordsFromCellIDString(key) for rownum := 0; rownum <= cell.VMerge; rownum++ { for colnum := 0; colnum <= cell.HMerge; colnum++ { // make cell s.Cell(mainrow+rownum, maincol+colnum) } } } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
sheet.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/sheet.go#L204-L415
go
train
// Dump sheet to its XML representation, intended for internal use only
func (s *Sheet) makeXLSXSheet(refTable *RefTable, styles *xlsxStyleSheet) *xlsxWorksheet
// Dump sheet to its XML representation, intended for internal use only func (s *Sheet) makeXLSXSheet(refTable *RefTable, styles *xlsxStyleSheet) *xlsxWorksheet
{ worksheet := newXlsxWorksheet() xSheet := xlsxSheetData{} maxRow := 0 maxCell := 0 var maxLevelCol, maxLevelRow uint8 // Scan through the sheet and see if there are any merged cells. If there // are, we may need to extend the size of the sheet. There needs to be // phantom cells underlying the area covered by the merged cell s.handleMerged() for index, sheetView := range s.SheetViews { if sheetView.Pane != nil { worksheet.SheetViews.SheetView[index].Pane = &xlsxPane{ XSplit: sheetView.Pane.XSplit, YSplit: sheetView.Pane.YSplit, TopLeftCell: sheetView.Pane.TopLeftCell, ActivePane: sheetView.Pane.ActivePane, State: sheetView.Pane.State, } } } if s.Selected { worksheet.SheetViews.SheetView[0].TabSelected = true } if s.SheetFormat.DefaultRowHeight != 0 { worksheet.SheetFormatPr.DefaultRowHeight = s.SheetFormat.DefaultRowHeight } worksheet.SheetFormatPr.DefaultColWidth = s.SheetFormat.DefaultColWidth colsXfIdList := make([]int, len(s.Cols)) for c, col := range s.Cols { XfId := 0 if col.Min == 0 { col.Min = 1 } if col.Max == 0 { col.Max = 1 } style := col.GetStyle() //col's style always not nil if style != nil { xNumFmt := styles.newNumFmt(col.numFmt) XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles) } colsXfIdList[c] = XfId var customWidth bool if col.Width == 0 { col.Width = ColWidth customWidth = false } else { customWidth = true } // When the cols content is empty, the cols flag is not output in the xml file. if worksheet.Cols == nil { worksheet.Cols = &xlsxCols{Col: []xlsxCol{}} } worksheet.Cols.Col = append(worksheet.Cols.Col, xlsxCol{Min: col.Min, Max: col.Max, Hidden: col.Hidden, Width: col.Width, CustomWidth: customWidth, Collapsed: col.Collapsed, OutlineLevel: col.OutlineLevel, Style: XfId, }) if col.OutlineLevel > maxLevelCol { maxLevelCol = col.OutlineLevel } if nil != col.DataValidation { if nil == worksheet.DataValidations { worksheet.DataValidations = &xlsxCellDataValidations{} } colName := ColIndexToLetters(c) for _, dd := range col.DataValidation { if dd.minRow == dd.maxRow { dd.Sqref = colName + RowIndexToString(dd.minRow) } else { dd.Sqref = colName + RowIndexToString(dd.minRow) + cellRangeChar + colName + RowIndexToString(dd.maxRow) } worksheet.DataValidations.DataValidation = append(worksheet.DataValidations.DataValidation, dd) } worksheet.DataValidations.Count = len(worksheet.DataValidations.DataValidation) } } for r, row := range s.Rows { if r > maxRow { maxRow = r } xRow := xlsxRow{} xRow.R = r + 1 if row.isCustom { xRow.CustomHeight = true xRow.Ht = fmt.Sprintf("%g", row.Height) } xRow.OutlineLevel = row.OutlineLevel if row.OutlineLevel > maxLevelRow { maxLevelRow = row.OutlineLevel } for c, cell := range row.Cells { XfId := colsXfIdList[c] // generate NumFmtId and add new NumFmt xNumFmt := styles.newNumFmt(cell.NumFmt) style := cell.style if style != nil { XfId = handleStyleForXLSX(style, xNumFmt.NumFmtId, styles) } else if len(cell.NumFmt) > 0 && !compareFormatString(s.Cols[c].numFmt, cell.NumFmt) { XfId = handleNumFmtIdForXLSX(xNumFmt.NumFmtId, styles) } if c > maxCell { maxCell = c } xC := xlsxC{ S: XfId, R: GetCellIDStringFromCoords(c, r), } if cell.formula != "" { xC.F = &xlsxF{Content: cell.formula} } switch cell.cellType { case CellTypeInline: // Inline strings are turned into shared strings since they are more efficient. // This is what Excel does as well. fallthrough case CellTypeString: if len(cell.Value) > 0 { xC.V = strconv.Itoa(refTable.AddString(cell.Value)) } xC.T = "s" case CellTypeNumeric: // Numeric is the default, so the type can be left blank xC.V = cell.Value case CellTypeBool: xC.V = cell.Value xC.T = "b" case CellTypeError: xC.V = cell.Value xC.T = "e" case CellTypeDate: xC.V = cell.Value xC.T = "d" case CellTypeStringFormula: xC.V = cell.Value xC.T = "str" default: panic(errors.New("unknown cell type cannot be marshaled")) } xRow.C = append(xRow.C, xC) if nil != cell.DataValidation { if nil == worksheet.DataValidations { worksheet.DataValidations = &xlsxCellDataValidations{} } cell.DataValidation.Sqref = xC.R worksheet.DataValidations.DataValidation = append(worksheet.DataValidations.DataValidation, cell.DataValidation) worksheet.DataValidations.Count = len(worksheet.DataValidations.DataValidation) } if cell.HMerge > 0 || cell.VMerge > 0 { // r == rownum, c == colnum mc := xlsxMergeCell{} start := GetCellIDStringFromCoords(c, r) endCol := c + cell.HMerge endRow := r + cell.VMerge end := GetCellIDStringFromCoords(endCol, endRow) mc.Ref = start + cellRangeChar + end if worksheet.MergeCells == nil { worksheet.MergeCells = &xlsxMergeCells{} } worksheet.MergeCells.Cells = append(worksheet.MergeCells.Cells, mc) } } xSheet.Row = append(xSheet.Row, xRow) } // Update sheet format with the freshly determined max levels s.SheetFormat.OutlineLevelCol = maxLevelCol s.SheetFormat.OutlineLevelRow = maxLevelRow // .. and then also apply this to the xml worksheet worksheet.SheetFormatPr.OutlineLevelCol = s.SheetFormat.OutlineLevelCol worksheet.SheetFormatPr.OutlineLevelRow = s.SheetFormat.OutlineLevelRow if worksheet.MergeCells != nil { worksheet.MergeCells.Count = len(worksheet.MergeCells.Cells) } if s.AutoFilter != nil { worksheet.AutoFilter = &xlsxAutoFilter{Ref: fmt.Sprintf("%v:%v", s.AutoFilter.TopLeftCell, s.AutoFilter.BottomRightCell)} } worksheet.SheetData = xSheet dimension := xlsxDimension{} dimension.Ref = "A1:" + GetCellIDStringFromCoords(maxCell, maxRow) if dimension.Ref == "A1:A1" { dimension.Ref = "A1" } worksheet.Dimension = dimension return worksheet }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
xmlStyle.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/xmlStyle.go#L337-L368
go
train
// newNumFmt generate a xlsxNumFmt according the format code. When the FormatCode is built in, it will return a xlsxNumFmt with the NumFmtId defined in ECMA document, otherwise it will generate a new NumFmtId greater than 164.
func (styles *xlsxStyleSheet) newNumFmt(formatCode string) xlsxNumFmt
// newNumFmt generate a xlsxNumFmt according the format code. When the FormatCode is built in, it will return a xlsxNumFmt with the NumFmtId defined in ECMA document, otherwise it will generate a new NumFmtId greater than 164. func (styles *xlsxStyleSheet) newNumFmt(formatCode string) xlsxNumFmt
{ if compareFormatString(formatCode, "general") { return xlsxNumFmt{NumFmtId: 0, FormatCode: "general"} } // built in NumFmts in xmlStyle.go, traverse from the const. numFmtId, ok := builtInNumFmtInv[formatCode] if ok { return xlsxNumFmt{NumFmtId: numFmtId, FormatCode: formatCode} } // find the exist xlsxNumFmt for _, numFmt := range styles.NumFmts.NumFmt { if formatCode == numFmt.FormatCode { return numFmt } } // The user define NumFmtId. The one less than 164 in built in. numFmtId = builtinNumFmtsCount + 1 styles.Lock() defer styles.Unlock() for { // get a unused NumFmtId if _, ok = styles.numFmtRefTable[numFmtId]; ok { numFmtId++ } else { styles.addNumFmt(xlsxNumFmt{NumFmtId: numFmtId, FormatCode: formatCode}) break } } return xlsxNumFmt{NumFmtId: numFmtId, FormatCode: formatCode} }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L111-L117
go
train
//GetTime returns the value of a Cell as a time.Time
func (c *Cell) GetTime(date1904 bool) (t time.Time, err error)
//GetTime returns the value of a Cell as a time.Time func (c *Cell) GetTime(date1904 bool) (t time.Time, err error)
{ f, err := c.Float() if err != nil { return t, err } return TimeFromExcelTime(f, date1904), nil }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L133-L137
go
train
/* The following are samples of format samples. * "0.00e+00" * "0", "#,##0" * "0.00", "#,##0.00", "@" * "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)" * "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)" * "0%", "0.00%" * "0.00e+00", "##0.0e+0" */ // SetFloatWithFormat sets the value of a cell to a float and applies // formatting to the cell.
func (c *Cell) SetFloatWithFormat(n float64, format string)
/* The following are samples of format samples. * "0.00e+00" * "0", "#,##0" * "0.00", "#,##0.00", "@" * "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)" * "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)" * "0%", "0.00%" * "0.00e+00", "##0.0e+0" */ // SetFloatWithFormat sets the value of a cell to a float and applies // formatting to the cell. func (c *Cell) SetFloatWithFormat(n float64, format string)
{ c.SetValue(n) c.NumFmt = format c.formula = "" }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L168-L170
go
train
// SetDate sets the value of a cell to a float.
func (c *Cell) SetDate(t time.Time)
// SetDate sets the value of a cell to a float. func (c *Cell) SetDate(t time.Time)
{ c.SetDateWithOptions(t, DefaultDateOptions) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L177-L181
go
train
// 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) SetDateWithOptions(t time.Time, options DateTimeOptions)
{ _, offset := t.In(options.Location).Zone() t = time.Unix(t.Unix()+int64(offset), 0) c.SetDateTimeWithFormat(TimeToExcelTime(t.In(timeLocationUTC), c.date1904), options.ExcelTimeFormat) }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L233-L258
go
train
// SetInt sets a cell's value to an integer.
func (c *Cell) SetValue(n interface{})
// SetInt sets a cell's value to an integer. func (c *Cell) SetValue(n interface{})
{ switch t := n.(type) { case time.Time: c.SetDateTime(t) return case int, int8, int16, int32, int64: c.setNumeric(fmt.Sprintf("%d", n)) case float64: // When formatting floats, do not use fmt.Sprintf("%v", n), this will cause numbers below 1e-4 to be printed in // scientific notation. Scientific notation is not a valid way to store numbers in XML. // Also not not use fmt.Sprintf("%f", n), this will cause numbers to be stored as X.XXXXXX. Which means that // numbers will lose precision and numbers with fewer significant digits such as 0 will be stored as 0.000000 // which causes tests to fail. c.setNumeric(strconv.FormatFloat(t, 'f', -1, 64)) case float32: c.setNumeric(strconv.FormatFloat(float64(t), 'f', -1, 32)) case string: c.SetString(t) case []byte: c.SetString(string(t)) case nil: c.SetString("") default: c.SetString(fmt.Sprintf("%v", n)) } }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L261-L266
go
train
// setNumeric sets a cell's value to a number
func (c *Cell) setNumeric(s string)
// setNumeric sets a cell's value to a number func (c *Cell) setNumeric(s string)
{ c.Value = s c.NumFmt = builtInNumFmt[builtInNumFmtIndex_GENERAL] c.formula = "" c.cellType = CellTypeNumeric }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L306-L309
go
train
// SetFormula sets the format string for a cell.
func (c *Cell) SetFormula(formula string)
// SetFormula sets the format string for a cell. func (c *Cell) SetFormula(formula string)
{ c.formula = formula c.cellType = CellTypeNumeric }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L357-L362
go
train
// getNumberFormat will update the parsedNumFmt struct if it has become out of date, since a cell's NumFmt string is a // public field that could be edited by clients.
func (c *Cell) getNumberFormat() *parsedNumberFormat
// getNumberFormat will update the parsedNumFmt struct if it has become out of date, since a cell's NumFmt string is a // public field that could be edited by clients. func (c *Cell) getNumberFormat() *parsedNumberFormat
{ if c.parsedNumFmt == nil || c.parsedNumFmt.numFmt != c.NumFmt { c.parsedNumFmt = parseFullNumberFormatString(c.NumFmt) } return c.parsedNumFmt }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
cell.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/cell.go#L368-L375
go
train
// 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.
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. func (c *Cell) FormattedValue() (string, error)
{ fullFormat := c.getNumberFormat() returnVal, err := fullFormat.FormatValue(c) if fullFormat.parseEncounteredError != nil { return returnVal, *fullFormat.parseEncounteredError } return returnVal, err }
tealeg/xlsx
b7005b5d48cbd240baa323f68fb644fe072ef088
read.go
https://github.com/tealeg/xlsx/blob/b7005b5d48cbd240baa323f68fb644fe072ef088/read.go#L26-L132
go
train
//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
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 func (r *Row) ReadStruct(ptr interface{}) error
{ if ptr == nil { return errNilInterface } //check if the type implements XLSXUnmarshaler. If so, //just let it do the work. unmarshaller, ok := ptr.(XLSXUnmarshaler) if ok { return unmarshaller.Unmarshal(r) } v := reflect.ValueOf(ptr) if v.Kind() != reflect.Ptr { return errNotStructPointer } v = v.Elem() if v.Kind() != reflect.Struct { return errNotStructPointer } n := v.NumField() for i := 0; i < n; i++ { field := v.Type().Field(i) idx := field.Tag.Get("xlsx") //do a recursive check for the field if it is a struct or a pointer //even if it doesn't have a tag //ignore if it has a - or empty tag isTime := false switch { case idx == "-": continue case field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Struct: var structPtr interface{} if !v.Field(i).CanSet() { continue } if field.Type.Kind() == reflect.Struct { structPtr = v.Field(i).Addr().Interface() } else { structPtr = v.Field(i).Interface() } //check if the container is a time.Time _, isTime = structPtr.(*time.Time) if isTime { break } err := r.ReadStruct(structPtr) if err != nil { return err } continue case len(idx) == 0: continue } pos, err := strconv.Atoi(idx) if err != nil { return errInvalidTag } //check if desired position is not out of bounds if pos > len(r.Cells)-1 { continue } cell := r.Cells[pos] fieldV := v.Field(i) //continue if the field is not settable if !fieldV.CanSet() { continue } if isTime { t, err := cell.GetTime(false) if err != nil { return err } if field.Type.Kind() == reflect.Ptr { fieldV.Set(reflect.ValueOf(&t)) } else { fieldV.Set(reflect.ValueOf(t)) } continue } switch field.Type.Kind() { case reflect.String: value, err := cell.FormattedValue() if err != nil { return err } fieldV.SetString(value) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: value, err := cell.Int64() if err != nil { return err } fieldV.SetInt(value) case reflect.Float64: value, err := cell.Float() if err != nil { return err } fieldV.SetFloat(value) case reflect.Bool: value := cell.Bool() fieldV.SetBool(value) } } value := v.Interface() ptr = &value return nil }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/connect.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/connect.go#L67-L120
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (c *ConnectPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (c *ConnectPacket) Unpack(b io.Reader) error
{ var err error c.ProtocolName, err = decodeString(b) if err != nil { return err } c.ProtocolVersion, err = decodeByte(b) if err != nil { return err } options, err := decodeByte(b) if err != nil { return err } c.ReservedBit = 1 & options c.CleanSession = 1&(options>>1) > 0 c.WillFlag = 1&(options>>2) > 0 c.WillQos = 3 & (options >> 3) c.WillRetain = 1&(options>>5) > 0 c.PasswordFlag = 1&(options>>6) > 0 c.UsernameFlag = 1&(options>>7) > 0 c.Keepalive, err = decodeUint16(b) if err != nil { return err } c.ClientIdentifier, err = decodeString(b) if err != nil { return err } if c.WillFlag { c.WillTopic, err = decodeString(b) if err != nil { return err } c.WillMessage, err = decodeBytes(b) if err != nil { return err } } if c.UsernameFlag { c.Username, err = decodeString(b) if err != nil { return err } } if c.PasswordFlag { c.Password, err = decodeBytes(b) if err != nil { return err } } return nil }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/connect.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/connect.go#L123-L148
go
train
//Validate performs validation of the fields of a Connect packet
func (c *ConnectPacket) Validate() byte
//Validate performs validation of the fields of a Connect packet func (c *ConnectPacket) Validate() byte
{ if c.PasswordFlag && !c.UsernameFlag { return ErrRefusedBadUsernameOrPassword } if c.ReservedBit != 0 { //Bad reserved bit return ErrProtocolViolation } if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) { //Mismatched or unsupported protocol version return ErrRefusedBadProtocolVersion } if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" { //Bad protocol name return ErrProtocolViolation } if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 { //Bad size field return ErrProtocolViolation } if len(c.ClientIdentifier) == 0 && !c.CleanSession { //Bad client identifier return ErrRefusedIDRejected } return Accepted }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/puback.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/puback.go#L34-L39
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (pa *PubackPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (pa *PubackPacket) Unpack(b io.Reader) error
{ var err error pa.MessageID, err = decodeUint16(b) return err }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/puback.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/puback.go#L43-L45
go
train
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket
func (pa *PubackPacket) Details() Details
//Details returns a Details struct containing the Qos and //MessageID of this ControlPacket func (pa *PubackPacket) Details() Details
{ return Details{Qos: pa.Qos, MessageID: pa.MessageID} }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
store.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/store.go#L46-L51
go
train
// A key MUST have the form "X.[messageid]" // where X is 'i' or 'o'
func mIDFromKey(key string) uint16
// A key MUST have the form "X.[messageid]" // where X is 'i' or 'o' func mIDFromKey(key string) uint16
{ s := key[2:] i, err := strconv.Atoi(s) chkerr(err) return uint16(i) }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
store.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/store.go#L74-L102
go
train
// govern which outgoing messages are persisted
func persistOutbound(s Store, m packets.ControlPacket)
// govern which outgoing messages are persisted func persistOutbound(s Store, m packets.ControlPacket)
{ switch m.Details().Qos { case 0: switch m.(type) { case *packets.PubackPacket, *packets.PubcompPacket: // Sending puback. delete matching publish // from ibound s.Del(inboundKeyFromMID(m.Details().MessageID)) } case 1: switch m.(type) { case *packets.PublishPacket, *packets.PubrelPacket, *packets.SubscribePacket, *packets.UnsubscribePacket: // Sending publish. store in obound // until puback received s.Put(outboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid message type") } case 2: switch m.(type) { case *packets.PublishPacket: // Sending publish. store in obound // until pubrel received s.Put(outboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid message type") } } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
store.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/store.go#L105-L136
go
train
// govern which incoming messages are persisted
func persistInbound(s Store, m packets.ControlPacket)
// govern which incoming messages are persisted func persistInbound(s Store, m packets.ControlPacket)
{ switch m.Details().Qos { case 0: switch m.(type) { case *packets.PubackPacket, *packets.SubackPacket, *packets.UnsubackPacket, *packets.PubcompPacket: // Received a puback. delete matching publish // from obound s.Del(outboundKeyFromMID(m.Details().MessageID)) case *packets.PublishPacket, *packets.PubrecPacket, *packets.PingrespPacket, *packets.ConnackPacket: default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 1: switch m.(type) { case *packets.PublishPacket, *packets.PubrelPacket: // Received a publish. store it in ibound // until puback sent s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } case 2: switch m.(type) { case *packets.PublishPacket: // Received a publish. store it in ibound // until pubrel received s.Put(inboundKeyFromMID(m.Details().MessageID), m) default: ERROR.Println(STR, "Asked to persist an invalid messages type") } } }
eclipse/paho.mqtt.golang
adca289fdcf8c883800aafa545bc263452290bae
packets/pubcomp.go
https://github.com/eclipse/paho.mqtt.golang/blob/adca289fdcf8c883800aafa545bc263452290bae/packets/pubcomp.go#L34-L39
go
train
//Unpack decodes the details of a ControlPacket after the fixed //header has been read
func (pc *PubcompPacket) Unpack(b io.Reader) error
//Unpack decodes the details of a ControlPacket after the fixed //header has been read func (pc *PubcompPacket) Unpack(b io.Reader) error
{ var err error pc.MessageID, err = decodeUint16(b) return err }