Reading files | simple-excel-go | Spatie       

 SPATIE  

simple-excel-go
===============

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Simple-excel-go](https://spatie.be/docs/simple-excel-go/v1)  Reading files

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/simple-excel-go/v1) 

  Reading files    
- [ Introduction ](https://spatie.be/docs/simple-excel-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/simple-excel-go/v1/installation-and-setup)
- [ Reading files ](https://spatie.be/docs/simple-excel-go/v1/reading-files)
- [ Writing files ](https://spatie.be/docs/simple-excel-go/v1/writing-files)
- [ Testing ](https://spatie.be/docs/simple-excel-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/simple-excel-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/simple-excel-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/simple-excel-go/v1/support-us)

 Reading files
=============

###  On this page 

1. [ Reading a CSV ](#content-reading-a-csv)

Reading a CSV
-----------------------------------------------------------------------------------------------

Imagine you have a CSV with this content.

```
email,first_name
john@example.com,john
jane@example.com,jane
```

```
reader, err := simpleexcel.NewReader(pathToCSV)
if err != nil {
    return err
}
for row, err := range reader.Rows(ctx) {
    if err != nil {
        return err
    }
    email, _ := row.Get("email")
    fmt.Println(email)
}
```

`ctx` is a `context.Context`. `Rows` returns an `iter.Seq2[Row, error]`. Each row has ordered `Headers` and `Values` slices. Use `row.Get("email")` for a named column or `row.Values[0]` for a positional column. `Get` returns `(nil, false)` for missing headers. Duplicate headers remain in the slices, and `Get` selects the last duplicate.

With headers, short rows are padded with empty strings and extra values are discarded. CSV values remain strings, including identifiers such as `00123`.

### Reading an Excel file

Reading an Excel file is identical to reading a CSV file. Just make sure that the path given to `NewReader` ends with `xlsx`. ODS files use the same interface with an `ods` extension.

When a path has no extension, specify the format:

```
reader, err := simpleexcel.NewReader("uploaded-file", simpleexcel.ReaderOptions{
    Format: simpleexcel.XLSX,
})
```

`NewReader` validates the format and CSV separators. Opening the file is deferred until rows or metadata are requested. A missing or corrupt file produces an error then.

### Working with iterators

`Rows` reads until you stop iteration or an error occurs. Always handle the error, even if you only want a subset of rows.

Here's a quick, silly example where we only want to process rows that have a `first_name` containing more than five characters:

```
for row, err := range reader.Rows(ctx) {
    if err != nil {
        return err
    }
    value, _ := row.Get("first_name")
    if name, ok := value.(string); ok && len(name) > 5 {
        fmt.Println(name)
    }
}
```

Each `Rows` call opens an independent iterator with the same skip and take settings. You can read a file again after requesting headers or breaking a previous iteration. `break` releases the file immediately. The reader itself needs no `Close` method. Do not mutate its settings while an iterator is running. Cancellation is checked between rows, not during a blocking filesystem operation or archive opening.

CSV and ODS reads use memory proportional to the current record and metadata. ODS sheet discovery scans `content.xml` before reading the selected sheet. Typed XLSX reads use Excelize cell and style access, which retains worksheet data and shared strings in memory. An iterator avoids a second result collection but does not make XLSX reads constant-memory.

### Reading a file without headers

If the file does not contain a header row, use `NoHeaderRow()`:

```
reader.NoHeaderRow()
```

Rows then have a nil `Headers` slice and positional `Values`. Header offsets have no effect in this mode.

### Manually setting the headers

If you would like to use a specific list of headers, use `UseHeaders()`:

```
reader.UseHeaders("email_address", "given_name")
```

If your file already contains a header row, it will be ignored and replaced with your custom headers. If it does not contain a header row, also use `NoHeaderRow()`.

### Working with multiple sheet documents

Excel files can include multiple spreadsheets. Select the sheet by a one-based index or its exact name:

```
reader.FromSheet(3)
reader.FromSheetName("Posts")

names, err := reader.SheetNames()
hasPosts, err := reader.HasSheet("Posts")
```

The last selection method wins. An absent sheet returns an error matching `ErrSheetNotFound`. CSV has one sheet named `Sheet1`.

### Retrieving header row values

Use `Headers(ctx)` to retrieve headers. If you used `UseHeaders`, these are returned instead of the actual file headers. `OriginalHeaders(ctx)` returns the file's headers after trimming and formatting, before custom replacement.

```
headers, err := reader.Headers(ctx)
originalHeaders, err := reader.OriginalHeaders(ctx)
```

An empty file has nil original headers. `NoHeaderRow()` also makes original headers nil.

### Dealing with headers that are not on the first line

Use `HeaderOnRow()` to indicate where the headers are present. Any data above that row is discarded. The index starts at zero. Blank rows do not count unless `PreserveEmptyRows` is enabled.

```
reader.HeaderOnRow(2).TrimHeaderRow()
```

This skips two nonempty rows above the header.

### Trimming headers

Use `TrimHeaderRow()` to remove space, tab, newline, carriage return, NUL and vertical tab from both ends of headers. Pass a character set to trim other characters. ASCII ranges such as `a..z` are supported. Unicode characters are treated as characters rather than UTF-8 bytes.

```
reader.TrimHeaderRow(" *")
```

### Convert headers to snake\_case

Use `HeadersToSnakeCase()` to convert headers such as `First Name`, `jobTitle` and `Column2` into `first_name`, `job_title` and `column_2`.

### Manually formatting headers

Use `FormatHeadersUsing()` with a function. Formatting runs after trimming and snake\_case conversion.

```
reader.FormatHeadersUsing(func(header string) string {
    return header + "_simple_excel"
})
```

### Trimming and formatting values

Just like you can clean up header names, you can clean up data values themselves. `TrimValues()` strips whitespace from string values. `TrimValues("*")` strips a character set from both ends, not a suffix. Non-string values, such as dates, are untouched.

For full control, use `FormatValuesUsing()`. The function receives the value and its header key. Without headers, the key is the decimal column index.

```
reader.TrimValues().FormatValuesUsing(func(value any, key string) any {
    if key == "email" {
        if text, ok := value.(string); ok {
            return strings.ToLower(text)
        }
    }
    return value
})
```

### Manually working with the reader object

Use `ReaderOptions.ConfigureXLSX` to configure the native `*excelize.File` each time an XLSX file opens. The callback runs before sheet selection and row reading. Do not close the file yourself.

For a different engine, supply `ReaderOptions.Open`. It returns your implementation of `ReadBackend`. Header handling, trimming, skip and take still apply to the replacement's output. Each iterator owns its backend and closes it on completion or early break. Read-side close errors are ignored during row iteration, as with ordinary read-only files.

### Limiting the result set

`Take` limits the number of data rows. `Skip` defines where to start after the header:

```
reader.Skip(10).Take(5)
```

This returns data rows 11 through 15. Both settings are reapplied on every iteration. `Take(0)` returns no rows. Negative header offsets, skip counts and limits return errors when the file is opened.

### Reading cells that contain formulas

Normally, cells containing formulas return the cached computed value stored in the file. This package does not evaluate formulas. Files without cached results may return an empty value or the engine's stored default.

Set `ReaderOptions.KeepFormulas` to return a `Formula` string beginning with `=`. The ODS namespace prefix is removed. Spreadsheet errors such as `#DIV/0!` remain strings.

### Preserve date formatting

By default spreadsheet dates are returned as `time.Time`. Excel dates have no timezone, and are represented in UTC without timezone conversion. Elapsed XLSX formats such as `[h]:mm:ss` and ODS time cells return `time.Duration`.

Set `ReaderOptions.PreserveDateTimeFormatting` to return XLSX date strings using the stored number format. Formatting follows Excelize, including its locale defaults. Built-in format 14 displays as `09-20-24` for September 20, 2024, rather than OpenSpout's default. This option does not format ODS dates.

### Preserve empty rows

Set `ReaderOptions.PreserveEmptyRows` to include blank CSV records and spreadsheet rows within the stored range. Leading and interior empty cells retain their positions. Spreadsheet rows omit trailing empty cells, while keyed rows pad to the header width.

### Using an alternative delimiter, enclosure or encoding

CSV defaults to a comma delimiter, double quote enclosure and UTF-8 encoding. Use options to change them:

```
reader, err := simpleexcel.NewReader(pathToCSV, simpleexcel.ReaderOptions{
    Delimiter: ';',
    Enclosure: '\'',
    Encoding:  "SHIFT_JIS",
})
```

Encoding labels follow the WHATWG registry. Conversion is incremental, and a decoded BOM is removed. Delimiter and enclosure must be distinct Unicode runes other than NUL, CR, LF or the Unicode replacement character. Malformed quoted fields return errors rather than silently discarding data.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
