Writing 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)  Writing files

 Version   v1      

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

  Writing 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)

 Writing files
=============

###  On this page 

1. [ Writing files ](#content-writing-files)

Writing files
-----------------------------------------------------------------------------------------------

Here's how you can write a CSV file:

```
writer, err := simpleexcel.NewWriter(pathToCSV)
if err != nil {
    return err
}
defer writer.Close()

if err := writer.AddRow(simpleexcel.Row{
    Headers: []string{"first_name", "last_name"},
    Values:  []any{"John", "Doe"},
}); err != nil {
    return err
}
if err := writer.AddRow(simpleexcel.Row{Values: []any{"Jane", "Doe"}}); err != nil {
    return err
}
return writer.Close()
```

The file contains:

```
first_name,last_name
John,Doe
Jane,Doe
```

`Row` uses slices because Go map iteration does not preserve column order. The first keyed row supplies automatic headers. Later rows retain the supplied value order, rather than being reordered by header name. Headers and values must have equal lengths when headers are supplied.

Text is always literal, including text beginning with `=`. Use `simpleexcel.Formula("=A2*3")` explicitly for spreadsheet formulas. CSV has no formula cell type, so spreadsheet applications may interpret exported text as formulas. Sanitize untrusted CSV exports for the destination application.

### Manually set the header from array

Instead of automatically detecting a header row, set it manually:

```
if err := writer.AddHeader("first_name", "last_name"); err != nil {
    return err
}
if err := writer.AddRow(simpleexcel.Row{Values: []any{"John", "Doe"}}); err != nil {
    return err
}
```

An unkeyed row does not generate an automatic header.

### Writing an Excel file

Writing an Excel file is identical to writing CSV. Just make sure that the path given to `NewWriter` ends with `xlsx`. ODS uses an `ods` extension. `WriterOptions.Format` overrides extension detection.

Always call `Close()` before accessing the output file and to receive finalization errors. Go garbage collection does not close the writer. A deferred close helps clean up early returns, but an explicit final close is still needed to check the result. Repeated closes return the same result. Adding rows after closing returns an error matching `ErrClosed`.

Failed writes may leave partial output. Writing is not transactional. Writer methods are not safe for concurrent calls.

CSV writes use memory proportional to the current row and buffer. XLSX uses Excelize's stream writer, spilling large row buffers to temporary disk. ODS spools each sheet's row XML to a temporary file. Styles, workbook metadata and ZIP finalization still allocate memory. Temporary disk usage grows with the export, and `Close` removes temporary files.

Spreadsheet numbers use floating-point storage. Write identifiers as text when precision matters. XLSX worksheet limits are 1,048,576 rows and 16,384 columns. The ODS reader enforces the same limits and rejects larger repeat counts.

### Streaming an Excel file to the browser

Instead of writing a named file, provide an `io.Writer`, such as an HTTP response:

```
response.Header().Set("Content-Type", "text/csv")
response.Header().Set("Content-Disposition", `attachment; filename="people.csv"`)
writer, err := simpleexcel.NewStreamWriter("people.csv", response)
if err != nil {
    return err
}
defer writer.Close()

if err := writer.AddRow(simpleexcel.Row{
    Headers: []string{"first_name", "last_name"},
    Values:  []any{"Jane", "Doe"},
}); err != nil {
    return err
}
return writer.Close()
```

The caller supplies HTTP headers and owns the sink. Closing this writer never closes the supplied sink or exits the process. Use the XLSX content type `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` or ODS content type `application/vnd.oasis.opendocument.spreadsheet` for those formats.

Use `Flush()` periodically for CSV streams, then flush your HTTP response through `http.Flusher` if supported. For XLSX and ODS, the completed ZIP archive is written to the sink at `Close()`. `Flush()` does not send a partial spreadsheet archive. Streaming to a sink does not imply that every format sends bytes before close.

### Writing multiple rows at once

Use `AddRows` with an `iter.Seq[Row]` to consume rows incrementally. A slice can be passed through `slices.Values`:

```
err := writer.AddRows(ctx, slices.Values([]simpleexcel.Row{
    {Headers: []string{"name"}, Values: []any{"John"}},
    {Values: []any{"Jane"}},
}))
```

The context is checked between rows. For an input sequence that also yields errors, use a loop and call `AddRow` after checking each error.

### Writing a file without titles

Use `NoHeaderRow()` if a title row should not be added automatically:

```
writer.NoHeaderRow()
err := writer.AddRow(simpleexcel.Row{
    Headers: []string{"first_name"},
    Values:  []any{"Jane"},
})
```

This outputs only `Jane`. `WriterOptions.NoHeader` sets the same behavior at creation.

### Adding layout

Use the native XLSX workbook to create styles, then pass the resulting style ID to `AddRow`. `SetHeaderStyle` applies to both automatic and explicit headers:

```
workbook, stream, err := writer.XLSX()
if err != nil {
    return err
}
styleID, err := workbook.NewStyle(&excelize.Style{
    Font: &excelize.Font{Bold: true, Size: 15, Color: "0000FF"},
    Alignment: &excelize.Alignment{WrapText: true},
    Fill: excelize.Fill{Type: "pattern", Pattern: 1, Color: []string{"FFFF00"}},
})
if err != nil {
    return err
}
writer.SetHeaderStyle(styleID)
```

Import `github.com/xuri/excelize/v2` for native layout types. `WriterOptions.ConfigureXLSX` runs before the stream is created. Use it for workbook-wide settings. It must leave exactly one initial sheet and must not write cell data through the normal Excelize API. Add sheets through `writer.AddSheet` instead. Native stream access is intended for layout and advanced cell operations, not normal row insertion.

ODS styles use native OpenDocument XML rather than Excelize IDs. Supply trusted style definitions in `WriterOptions.ODSStyles`, then use a style name for `SetHeaderStyle` or the optional `AddRow` style:

```
options := simpleexcel.WriterOptions{
    ODSStyles: `<style:style style:name="heading" style:family="table-cell"><style:text-properties fo:font-weight="bold"/></style:style>`,
    HeaderStyle: "heading",
}
```

The definitions are placed inside `office:styles` in `styles.xml`. ODF `style`, `fo`, `table`, `text`, `office` and `of` namespaces are declared. Do not accept raw style XML from untrusted input. CSV ignores styles. An incompatible style type returns an error for XLSX or ODS.

### Setting column widths and row heights

Access the underlying XLSX stream to set column widths before adding rows:

```
if err := stream.SetColWidth(1, 8, 25); err != nil {
    return err
}
```

Native Excelize coordinates start at one. Row heights and per-cell styles are available through Excelize's `RowOpts` and `Cell` types when using the native stream directly. Those writes bypass this package's row count and header tracking. Do not mix normal workbook cell writes with stream writes on a sheet, or flush and close the native stream yourself.

For ODS layout beyond cell styles, use a custom `WriteBackend` with the native ODF layout behavior you need.

### Creating additional sheets

By default the writer writes to the first sheet. Use `NameCurrentSheet` to rename it, and `AddSheet` for another sheet:

```
if err := writer.NameCurrentSheet("Posts"); err != nil {
    return err
}
if err := writer.AddSheet("Comments"); err != nil {
    return err
}
```

Pass an empty name to create names such as `Sheet2`. Each sheet starts with automatic header detection unless `NoHeaderRow` was set globally. CSV does not support sheet naming or additional sheets.

### Using an alternative delimiter

Configure the CSV delimiter and enclosure at creation:

```
writer, err := simpleexcel.NewWriter(pathToCSV, simpleexcel.WriterOptions{
    Delimiter: ';',
    WithoutBOM: true,
})
```

### Getting the number of rows written

`NumberOfRows()` returns the total across all sheets, including automatic and explicit header rows. One keyed row with an automatic header counts as two rows. Writes made directly through the native engine are not counted.

### Disable BOM

Set `WriterOptions.WithoutBOM` to disable the UTF-8 BOM. This must be configured at creation. CSV defaults to a BOM, comma delimiter, double quote enclosure and LF record endings.

### Manually working with the writer object

`XLSX()` returns the workbook and current stream. Layout settings apply to that stream. After adding a sheet, request the handles again to obtain the new current stream.

For a different engine, supply `WriterOptions.Backend`. The factory receives the output sink and returns a `WriteBackend`. Wrapper headers, row counts and sheet tracking still apply. The backend must not close the caller's sink, and its `Close` method must finalize its format and release its own resources.

 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)
