excel

package
v0.0.0-...-629ae18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

ContentType is the MIME type for Excel files.

Variables

This section is empty.

Functions

func DerefValueAndType

func DerefValueAndType(val any) (reflect.Value, reflect.Type)

DerefValueAndType dereferences pointers and returns the final value and type.

This utility function is useful for handling pointer types in Excel rendering, ensuring that the actual underlying value and type are used for formatting decisions. It recursively dereferences pointers until it reaches a non-pointer value.

Parameters:

  • val: The value to dereference

Returns:

  • reflect.Value: The dereferenced value
  • reflect.Type: The type of the dereferenced value

Example:

value, valueType := excel.DerefValueAndType(somePointer)
if valueType.Kind() == reflect.String {
    // Handle string type
}

func ValueOf

func ValueOf(val any) reflect.Value

ValueOf returns the argument casted to reflect.Value if it's already a reflect.Value, otherwise returns the standard result of reflect.ValueOf(val).

This utility function is useful when working with interfaces that might contain either regular values or reflect.Value instances, ensuring consistent handling.

Parameters:

  • val: The value to convert to reflect.Value

Returns:

  • reflect.Value: The reflect.Value representation of the input

Example:

value := excel.ValueOf(someInterface)
if value.IsValid() {
    // Process the value
}

Types

type ExcelCellWriter

type ExcelCellWriter interface {
	// WriteCell writes a value to an Excel cell with the given formatting configuration.
	WriteCell(cell *xlsx.Cell, val reflect.Value, config *ExcelFormatConfig) error
}

ExcelCellWriter defines the interface for writing specific data types to Excel cells.

This interface allows for custom formatting of different Go types when writing them to Excel cells, providing fine-grained control over cell appearance and data types.

type ExcelCellWriterFunc

type ExcelCellWriterFunc func(cell *xlsx.Cell, val reflect.Value, config *ExcelFormatConfig) error

ExcelCellWriterFunc implements ExcelCellWriter with a function.

This allows you to use a simple function as an ExcelCellWriter without creating a custom type.

func (ExcelCellWriterFunc) WriteCell

func (f ExcelCellWriterFunc) WriteCell(cell *xlsx.Cell, val reflect.Value, config *ExcelFormatConfig) error

WriteCell calls the underlying function to write a cell value.

type ExcelFormatConfig

type ExcelFormatConfig struct {
	// Time specifies the Excel format string for time values.
	// See https://exceljet.net/custom-number-formats for format options.
	Time string
	// Date specifies the Excel format string for date values.
	Date string
	// Location specifies the timezone for date/time formatting.
	Location *time.Location
	// Null specifies the string representation for null values.
	Null string
}

ExcelFormatConfig contains configuration for Excel cell formatting.

This struct provides settings for formatting different data types in Excel cells, including date/time formats, number formats, and null value representations.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Reader implements the structtable.Reader interface for Excel (.xlsx) files.

This reader can parse Excel files and populate struct instances with the data. It supports reading from specific sheets and handles various data types.

func NewReader

func NewReader(xlsxFile fs.FileReader, sheetName string) (*Reader, error)

NewReader creates a new structtable.Reader for the specified sheet in an Excel file.

This constructor opens an Excel file and creates a Reader instance for the specified sheet. If sheetName is empty, the first sheet will be used.

Note: Currently, this reader only populates string-type struct fields.

Parameters:

  • xlsxFile: The Excel file to read from
  • sheetName: The name of the sheet to read (empty string for first sheet)

Returns:

  • A new Reader instance ready for use
  • err: Any error that occurred during file opening or sheet access

func (*Reader) NumRows

func (r *Reader) NumRows() int

NumRows returns the total number of rows in the Excel sheet.

This method returns the maximum row index in the sheet, which represents the total number of rows available for reading. Note that this includes empty rows, so the actual number of rows with data may be less.

Returns:

  • int: The total number of rows in the sheet (1-based, so MaxRow is the count)

Example:

reader, err := excel.NewReader(file, "Sheet1")
if err != nil {
    return err
}
totalRows := reader.NumRows()
fmt.Printf("Sheet has %d rows\n", totalRows)

func (*Reader) ReadRow

func (r *Reader) ReadRow(rowIndex int, destStruct reflect.Value) error

ReadRow populates a struct instance with data from the specified Excel row.

This method reads data from the specified row and populates the fields of the provided struct instance. It maps Excel columns to struct fields by position (first column to first field, second column to second field, etc.).

Important Limitations:

  • Only populates string-type struct fields
  • Field mapping is positional (column index = field index)
  • Stops reading when either MaxCol or NumField() is reached
  • All cell values are converted to strings using String() method

Parameters:

  • rowIndex: The zero-based index of the row to read
  • destStruct: A reflect.Value pointing to the struct instance to populate

Returns:

  • err: Any error that occurred during reading or bounds checking

Bounds Checking:

  • Returns error if rowIndex is negative or >= MaxRow
  • Only reads up to the minimum of MaxCol and destStruct.NumField()

Example:

type Person struct {
    Name string
    Age  string  // Note: string type required
    City string
}
var person Person
err := reader.ReadRow(0, reflect.ValueOf(&person).Elem())

func (*Reader) ReadRowStrings

func (r *Reader) ReadRowStrings(rowIndex int) ([]string, error)

ReadRowStrings returns raw string values for a specific row in the Excel sheet.

This method reads all cells from the specified row and returns them as a slice of strings. It reads from all columns up to MaxCol, filling empty cells with empty strings. This is useful when you need access to the raw data without struct mapping.

Parameters:

  • rowIndex: The zero-based index of the row to read

Returns:

  • []string: Slice of string values from the row (one per column)
  • err: Any error that occurred during reading or bounds checking

Bounds Checking:

  • Returns error if rowIndex is negative or >= MaxRow
  • Reads all columns from 0 to MaxCol-1

Example:

rowData, err := reader.ReadRowStrings(0) // Read first row
if err != nil {
    return err
}
fmt.Printf("Row contains %d columns\n", len(rowData))

func (*Reader) SheetName

func (r *Reader) SheetName() string

SheetName returns the name of the current Excel sheet.

This method returns the name of the sheet that this reader is currently reading from. This is useful for debugging, logging, or when you need to identify which sheet the data came from.

Returns:

  • string: The name of the Excel sheet

Example:

reader, err := excel.NewReader(file, "Sales Data")
if err != nil {
    return err
}
fmt.Printf("Reading from sheet: %s\n", reader.SheetName())

type Renderer

type Renderer struct {
	Config          ExcelFormatConfig
	TypeCellWriters map[reflect.Type]ExcelCellWriter
	// contains filtered or unexported fields
}

Renderer implements the structtable.Renderer interface for Excel files.

This renderer generates Excel (.xlsx) files from struct slices, with support for custom formatting, multiple sheets, and various data types.

func NewRenderer

func NewRenderer(sheetName string) (*Renderer, error)

NewRenderer creates a new Excel Renderer with default formatting and styling.

This constructor sets up a new Excel file with header styles, cell writers for common types, and creates the initial sheet. The renderer is configured with sensible defaults for date/time formatting and includes built-in cell writers for common data types.

Parameters:

  • sheetName: Name for the initial sheet (will be sanitized to comply with Excel naming rules)

Returns:

  • A new Renderer instance ready for use
  • err: Any error that occurred during initialization (e.g., invalid sheet name)

Example:

renderer, err := excel.NewRenderer("Sales Data")
if err != nil {
    return err
}

func (*Renderer) AddSheet

func (excel *Renderer) AddSheet(name string) error

AddSheet adds a new sheet to the Excel file and sets it as the current sheet.

This method creates a new worksheet with the specified name and makes it the active sheet for subsequent rendering operations. The sheet name will be sanitized to comply with Excel naming rules (removing invalid characters, limiting length).

Parameters:

  • name: The name for the new sheet

Returns:

  • err: Any error that occurred during sheet creation

Example:

err := renderer.AddSheet("Q1 Results")
if err != nil {
    return err
}

func (*Renderer) MIMEType

func (*Renderer) MIMEType() string

MIMEType returns the MIME type for Excel files.

This method returns the standard MIME type for Excel (.xlsx) files, which is used for HTTP content-type headers and file type identification.

Returns:

  • string: The MIME type "vnd.openxmlformats-officedocument.spreadsheetml.sheet"

Example:

contentType := renderer.MIMEType()
w.Header().Set("Content-Type", contentType)

func (*Renderer) RenderHeaderRow

func (excel *Renderer) RenderHeaderRow(columnTitles []string) error

RenderHeaderRow renders a header row with bold styling to the current sheet.

This method creates a new row in the current sheet and populates it with the provided column titles. The header row uses the configured header style (bold font, Liberation Sans, size 10) to distinguish it from data rows.

Parameters:

  • columnTitles: Slice of strings representing the column headers

Returns:

  • err: Any error that occurred during rendering

Example:

headers := []string{"Name", "Age", "Department", "Salary"}
err := renderer.RenderHeaderRow(headers)

func (*Renderer) RenderRow

func (excel *Renderer) RenderRow(columnValues []reflect.Value) error

RenderRow renders a data row to the current sheet with appropriate formatting.

This method creates a new row in the current sheet and populates it with the provided column values. It applies intelligent formatting based on the data type: - Uses custom cell writers for registered types (dates, money, etc.) - Handles nullable values with configurable null representation - Applies appropriate Excel data types (numbers, strings, booleans) - Sets right alignment for numeric values - Falls back to String() method or fmt.Sprint for unknown types

Parameters:

  • columnValues: Slice of reflect.Value instances representing the row data

Returns:

  • err: Any error that occurred during rendering

Example:

values := []reflect.Value{
    reflect.ValueOf("John Doe"),
    reflect.ValueOf(25),
    reflect.ValueOf(time.Now()),
}
err := renderer.RenderRow(values)

func (*Renderer) Result

func (excel *Renderer) Result() ([]byte, error)

Result returns the Excel file as a byte slice.

This method generates the complete Excel (.xlsx) file in memory and returns it as a byte slice. This is useful when you need to store the file in memory, send it over a network, or process it further before writing to disk.

Returns:

  • []byte: The complete Excel file as bytes
  • err: Any error that occurred during file generation

Example:

data, err := renderer.Result()
if err != nil {
    return err
}
// Use data bytes for further processing

func (*Renderer) SetCurrentSheet

func (excel *Renderer) SetCurrentSheet(name string) error

SetCurrentSheet sets the current sheet by name for subsequent rendering operations.

This method switches the active sheet to an existing sheet with the specified name. All subsequent calls to RenderHeaderRow and RenderRow will operate on this sheet.

Parameters:

  • name: The name of the sheet to make current

Returns:

  • err: Any error that occurred (e.g., sheet not found)

Example:

err := renderer.SetCurrentSheet("Summary")
if err != nil {
    return err
}

func (*Renderer) WriteResultFile

func (excel *Renderer) WriteResultFile(file fs.File, perm ...fs.Permissions) error

WriteResultFile writes the Excel file to a file using fs.File interface.

This method generates the complete Excel (.xlsx) file and writes it to the specified file using the fs.File interface. It handles file opening, writing, and closing automatically. Optional file permissions can be specified.

Parameters:

  • file: The fs.File to write the Excel file to
  • perm: Optional file permissions (uses default if not provided)

Returns:

  • err: Any error that occurred during file operations or writing

Example:

outputFile := fs.NewFile("reports/sales.xlsx")
err := renderer.WriteResultFile(outputFile, fs.Permissions(0644))

func (*Renderer) WriteResultTo

func (excel *Renderer) WriteResultTo(writer io.Writer) error

WriteResultTo writes the Excel file to an io.Writer.

This method generates the complete Excel (.xlsx) file and writes it directly to the provided io.Writer. This is more memory-efficient than Result() when writing to files or network streams, as it doesn't need to hold the entire file in memory.

Parameters:

  • writer: The io.Writer to write the Excel file to

Returns:

  • err: Any error that occurred during writing

Example:

file, err := os.Create("output.xlsx")
if err != nil {
    return err
}
defer file.Close()
err = renderer.WriteResultTo(file)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL