pytablewriter

repository·master·Indexed 20 days ago

https://github.com/thombashi/pytablewriter

A versatile Python library for exporting tabular data into various formats, including text (Markdown, HTML, CSV), binary (Excel, SQLite), and data-science specific formats (Pandas, NumPy). It supports data sources such as CSV text, CSV files, and pandas DataFrames, and provides specialized writers like MarkdownTableWriter, ExcelXlsxTableWriter, and SqliteTableWriter.

Tokens
25K
Snippets
86
Records
119
Agent score
69%

What's inside pytablewriter

  1. Overview of pytablewriter features

    master

    pytablewriter is a Python library designed to write tabular data into a wide variety of formats. It supports text-based formats (Markdown, HTML, CSV, JSON, YAML, LaTeX, etc.), binary formats (Excel, SQLite, Pandas pickle), and application-specific formats like Elasticsearch.

    Key capabilities include:

    • Automatic Formatting: Handles cell alignment, padding, and decimal places.
    • Styling: Customize text/background colors, font weight, and number separators.
    • Flexible Output: Write to files, standard output, string buffers, or Jupyter Notebooks.
    • Diverse Data Sources: Accepts nested lists, CSV files, and Pandas DataFrames/Series.
  2. Supported table output formats in pytablewriter

    master

    pytablewriter supports writing tables to various formats, categorized into text-based, binary, and application-specific formats.

    Text Formats

    • csv (Comma Separated Values)
    • ltsv (Labeled Tab Separated Values)
    • latex (LaTeX tables)
    • markup (Various markup languages)
    • json (JSON arrays/objects)
    • code (Code-style representations)
    • rst (reStructuredText)
    • spacealigned (Space-aligned text tables)
    • toml (TOML configuration format)
    • yaml (YAML format)
    • unicode (Unicode-based box-drawing tables)
    • borderless (Tables without borders)
    • css (CSS-based representations)

    Binary Formats

    • excel (Microsoft Excel files)
    • pandas_pickle (Pandas Pickle files)
    • sqlite (SQLite databases)

    Application Specific Formats

    • es (Elasticsearch specific formats)
  3. Understand the TableWriterInterface

    master
    The pytablewriter.writer._interface.TableWriterInterface defines the structural contract for all table writers in the library. It ensures that different writer implementations (e.g., CSV, HTML, Markdown) provide a consistent set of methods for handling table data, headers, and formatting, allowing them to be used interchangeably within the library's ecosystem.
  4. Configure table cell styling with Style and Cell classes

    master

    The pytablewriter.style module provides classes to control the visual appearance of tables. You can use Style to define general table aesthetics and Cell to apply specific styles to individual cells.

    Key styling components include:

    • Align: Horizontal alignment (e.g., left, center, right).
    • VerticalAlign: Vertical alignment within a cell.
    • FontWeight, FontSize, and FontStyle: Text properties.
    • ThousandSeparator: Formatting for numeric values.
    • DecorationLine: Styling for lines/borders.

    To apply styles, you typically define a Style object or a Cell object and pass them to your table writer's configuration.

  5. Apply conditional styles using Style Filters

    master

    Style filters allow you to apply styles to specific cells based on their content or position. A style filter is a Python function that accepts a Cell object and returns an optional Style object.

    Filter Function Signature: def filter_func(cell: Cell, **kwargs: Any) -> Optional[Style]:

    Inside the function, you can inspect cell.col, cell.row, cell.value, or use cell.is_header_row() to determine which style to return. Register the filter using writer.add_style_filter(filter_func).

    from typing import Any, Optional
    from pytablewriter import MarkdownTableWriter
    from pytablewriter.style import Cell, Style
    
    def style_filter(cell: Cell, **kwargs: Any) -> Optional[Style]:
        if cell.is_header_row():
            return None
    
        if cell.col == 0:
            return Style(font_weight="bold")
    
        value = int(cell.value)
    
        if value > 80:
            return Style(fg_color="red", font_weight="bold", decoration_line="underline")
        elif value > 50:
            return Style(fg_color="yellow", font_weight="bold")
        elif value > 20:
            return Style(fg_color="green")
    
        return Style(fg_color="lightblue")
    
    writer = MarkdownTableWriter(
        table_name="style filter example",
        headers=["Key", "Value 1", "Value 2"],
        value_matrix=[
            ["A", 95, 40],
            ["B", 55, 5],
            ["C", 30, 85],
            ["D", 0, 69],
        ],
        flavor="github",
        enable_ansi_escape=False,
    )
    writer.add_style_filter(style_filter)
    writer.write_table()
  6. Customize table appearance with Theme

    master
    The pytablewriter.style.Theme class allows you to define the visual style of your tables. You can use it to control how cells, rows, and columns are styled, including colors, borders, and separators. Themes are typically passed to a TableWriter instance to apply a consistent look across your output.
  7. Implement a custom binary table writer

    master

    When extending pytablewriter to support new binary formats, you should implement or inherit from the provided binary writer interfaces.

    • BinaryWriterInterface: Defines the core interface requirements for binary writers.
    • AbstractBinaryTableWriter: An abstract base class that provides the foundation for concrete binary table writer implementations.

    Developers should use these classes to ensure their custom writers remain compatible with the library's expected lifecycle and structure for binary data output.

  8. Install optional dependencies for pytablewriter

    master

    You can install specific feature sets by using extras during installation. This allows you to keep your environment lightweight by only installing what you need for specific output formats or features.

    Available extras:

    • logging: Adds support for loguru logging.
    • from: Adds support for reading tables via pytablereader.
    • es: Adds support for Elasticsearch.
    • excel: Adds support for writing Excel files (xlwt, XlsxWriter).
    • html: Adds support for HTML table generation via dominate.
    • sqlite: Adds support for SQLite via SimpleSQLite.
    • theme: Adds support for alternative themes (pytablewriter-altrow-theme, pytablewriter-altcol-theme).
    • toml: Adds support for TOML files.
    # Example: Install with Excel and HTML support
    ```bash
    pip install pytablewriter[excel,html]
  9. Install optional dependencies for pytablewriter

    master

    pytablewriter supports several optional extras to enable specific features like Excel support, HTML generation, or database integration. You can install these using your preferred package manager by specifying the extra name.

    Supported extras:

    • logging: Adds loguru support for enhanced logging.
    • from: Adds pytablereader support to read data before writing.
    • es: Adds elasticsearch support.
    • excel: Adds xlwt and XlsxWriter support for Excel files.
    • html: Adds dominate support for HTML table generation.
    • sqlite: Adds SimpleSQLite support.
    • theme: Adds alternative row/column themes (pytablewriter-altrow-theme, pytablewriter-altcol-theme).
    • toml: Adds toml support.
  10. Render tables in Jupyter Notebook

    master

    All pytablewriter writer classes support rendering directly in Jupyter Notebook cells. To enable this, you must install the [html] or [all] extra:

    pip install pytablewriter[html]
    # OR
    pip install pytablewriter[all]
    pip install pytablewriter[html]
  11. Install and use predefined Themes

    master

    Themes are collections of style filters. To use external predefined themes, you must install the [theme] extra:

    pip install pytablewriter[theme]

    Once installed, you can apply a theme via the writer constructor using the theme argument or by calling set_theme(theme_name).

    Available themes include:

    • altrow: Colors rows alternatively.
    • altcol: Colors columns alternatively.

    Example using TableWriterFactory:

    import pytablewriter as ptw
    
    writer = ptw.TableWriterFactory.create_from_format_name(
        "markdown",
        headers=["INT", "STR"],
        value_matrix=[[1, "hoge"], [2, "foo"], [3, "bar"]],
        margin=1,
        theme="altrow",
    )
    writer.write_table()