write_xlsx Ruby Gem

repository·main·Indexed 43 days ago

https://github.com/cxn03651/write_xlsx

A Ruby port of the Perl module Excel::Writer::XLSX used to create new Excel files in the Excel 2007+ XLSX format. It provides a comprehensive interface for generating complex spreadsheets, including cell formatting via Format objects and the creation of embedded Area and Bar charts with support for stacked and percent_stacked subtypes.

Tokens
72.7K
Snippets
258
Records
281
Agent score
52%

What's inside write_xlsx

  1. Explore WriteXLSX example programs

    main

    The write_xlsx distribution includes 96 example programs covering a wide range of Excel features. These examples can be used as templates or references for implementing specific functionalities in your own Ruby applications.

    Key categories of examples include:

    • Basic Operations: Simple demos, formatting, and multiple worksheets.
    • Charts: Various styles including bar, column, line, pie, doughnut, radar, scatter, stock, and combined charts.
    • Advanced Formatting: Conditional formatting, cell merging, indentation, and rich strings.
    • Data & Formulas: Array formulas, dynamic arrays (Excel 365), data validation, and dropdown lists.
    • Worksheet Features: Headers/footers, outlines, panes, tables, and hiding rows/columns/sheets.
    • Shapes & Images: Inserting shapes, connectors, and embedding images.
    • Unicode Support: Examples for various encodings like Japanese (Shift JIS, ISO-2022-JP), Chinese (BIG5), Thai, Greek, Russian, and Arabic.
  2. Unique hyperlink limits per worksheet

    main
    While Excel allows a higher number of non-unique hyperlinks if they are contiguous and can be grouped into a single range, Excel::Writer::XLSX does not support this optimization. You must stay within the limit of 65,530 unique hyperlinks per worksheet.
  3. Configure Line chart series using array references

    main

    Instead of using Excel-style range strings, you can define chart series ranges using an array reference. The format is: [ sheetname, row_start, row_end, col_start, col_end ].

    Note that when using this array format, the row and column indices are 0-based.

    chart.add_series(
        name:       '=Sheet1!$C$1',
        categories: [ 'Sheet1', 1, 6, 0, 0 ],
        values:     [ 'Sheet1', 1, 6, 2, 2 ]
    )
  4. Configure cell formatting and styles

    main

    Formatting in WriteXLSX is handled by creating format objects via workbook.add_format. You can pass an options hash to add_format or use setter methods on the returned object (e.g., format.set_bold, format.set_color).

    Common formatting options include:

    • bold: Boolean (1 for true)
    • italic: Boolean
    • color: String (color name or hex)
    • size: Integer (font size)
    • font: String (font name)
    • align: String (e.g., 'center', 'vcenter')
    • num_format: String (Excel numeric format string)
    • bg_color: String (background color)
    • border: Integer (border style)
    • pattern: Integer (pattern type)
    # Creating format via hash
    text_format = workbook.add_format(
      bold:   1,
      italic: 1,
      color:  'red',
      size:   18,
      font:   'Lucida Calligraphy'
    )
    
    # Creating format via setter methods
    format = workbook.add_format
    format.set_bold
    format.set_size(14)
    format.set_color('blue')
    
    # Applying format to a cell
    worksheet.write('B3', "Hello Excel", text_format)
  5. Understand how Excel handles dates and times

    main

    In Excel, a date or time is not a string; it is a real number combined with an Excel number format.

    • The integer part of the number represents the number of days since the epoch.
    • The fractional part represents the percentage of the day (time).

    Warning: If you use the standard write() method with a date string (e.g., worksheet.write('A1', '02/03/04')), WriteXLSX will write it as a literal string, not a functional Excel date. To ensure Excel treats the data as a date, you must write the numeric representation and apply a num_format via a format object.

    # This writes a string, NOT a date
    worksheet.write('A1', '02/03/04') 
    
    # This writes a functional date (number + format)
    number = 39506.5
    format = workbook.add_format(num_format: 'dd/mm/yy')
    worksheet.write('A2', number, format)
  6. Define chart series ranges using array references

    main

    In addition to standard Excel range strings (e.g., '=Sheet1!$B$2:$B$7'), add_series supports an alternative array reference format for defining ranges. This is useful for programmatic range construction.

    An array reference follows this pattern: [ sheetname, row_start, row_end, col_start, col_end ].

    Note: Indices are 0-based.

    # Example using array references for categories and values
    chart.add_series(
        name:       '=Sheet1!$C$1',
        categories: [ 'Sheet1', 1, 6, 0, 0 ],
        values:     [ 'Sheet1', 1, 6, 2, 2 ]
    )
  7. Set font rotation in charts

    main

    The :rotation property allows you to rotate text within a chart, which is useful for displaying large datasets (like dates) compactly.

    Supported values:

    • Integer range -90 to 90.
    • 270: Stacked text (runs from top to bottom).
    • 271: A special variant of stacked text for East Asian fonts.
    chart.set_x_axis( num_font: { rotation: 45 } )
  8. Define chart series using array references

    main

    When calling add_series(), you can define data ranges using an array reference instead of Excel string notation. The format is: [ sheetname, row_start, row_end, col_start, col_end ].

    Note: Row and column indices are 0-indexed in this array format.

    chart.add_series(
        name:       'Doughnut sales data',
        categories: [ 'Sheet1', 1, 3, 0, 0 ], # Sheet1, rows 1-3, col 0
        values:     [ 'Sheet1', 1, 3, 1, 1 ]  # Sheet1, rows 1-3, col 1
    )
  9. Use Row-Column or A1 cell notation

    main

    WriteXLSX supports two ways to specify cell positions:

    1. Row-Column notation: Uses a zero-based index for both row and column (e.g., (0, 0) for the top-left cell).
    2. A1 notation: Uses standard Excel alphanumeric sequences (e.g., 'A1' for the top-left cell).

    Row-column notation is ideal for programmatic loops, while A1 notation is useful for manual setup and formulas.

    Note: R1C1 notation is not supported.

    # Row-column notation (zero-based)
    (0..9).each do |i|
      worksheet.write(i, 0, 'Hello') # Cells A1 to A10
    end
    
    # A1 notation
    worksheet.write('H1', 200)
    worksheet.write('H2', '=H1+1')
    
    # Column notation in formulas
    worksheet.write('A1', '=SUM(B:B)')
  10. Hyperlink character limits and version compatibility

    main

    The maximum length for a hyperlink URL depends on the Excel version being used:

    • Excel versions prior to 2015: Limited to 255 characters for both links and anchor/locations.
    • Excel versions 2015 and later: Support URLs up to 2,079 characters.

    Excel::Writer::XLSX versions >= 1.0.2 support the longer 2,079 character limit by default.

  11. Use named colors, the Excel color palette, and HTML colors

    main

    The write_xlsx library supports several ways to define colors for formats via the fg_color option in workbook.add_format():

    1. Named Colors: Use standard strings like 'black', 'blue', 'red', 'white', etc.
    2. Excel Color Palette: Use integer indices (e.g., 0x08, 0x0C) representing the built-in Excel color palette.
    3. HTML Colors: Use hex strings (e.g., '#FF0000', '#FFFFFF').
    # Using a named color
    format_named = workbook.add_format(fg_color: 'red')
    
    # Using an Excel palette index
    format_palette = workbook.add_format(fg_color: 0x0A)
    
    # Using an HTML hex color
    format_html = workbook.add_format(fg_color: '#FF0000')