### Install xlsx2csv as a Command-Line Tool
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Define the script entry point in pyproject.toml to install xlsx2csv as a command-line tool.
```toml
[project.scripts]
xlsx2csv = "xlsx2csv:main"
```
--------------------------------
### Time Format Examples
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Demonstrates setting custom time formats using strftime codes.
```python
# Time formats (strftime codes)
Xlsx2csv("file.xlsx", timeformat="%H:%M") # 14:30 (default)
Xlsx2csv("file.xlsx", timeformat="%H:%M:%S") # 14:30:45
Xlsx2csv("file.xlsx", timeformat="%I:%M %p") # 02:30 PM
```
--------------------------------
### Install for Local Development
Source: https://github.com/dilshod/xlsx2csv/blob/master/CLAUDE.md
Install the project in editable mode for local development. This allows changes to the source code to be reflected immediately without reinstallation.
```bash
pip install -e .
```
--------------------------------
### Install xlsx2csv via CLI
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
Use standard package managers to install the tool globally.
```sh
sudo easy_install xlsx2csv
```
```sh
pip install xlsx2csv
```
--------------------------------
### Date Format Examples
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Illustrates setting custom date formats using strftime codes for output.
```python
# Date formats (strftime codes)
Xlsx2csv("file.xlsx", dateformat="%Y-%m-%d") # 2023-05-15
Xlsx2csv("file.xlsx", dateformat="%d/%m/%Y") # 15/05/2023
Xlsx2csv("file.xlsx", dateformat="%m/%d/%Y") # 05/15/2023
Xlsx2csv("file.xlsx", dateformat="%d-%b-%Y") # 15-May-2023
```
--------------------------------
### Standard Delimiter Examples
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Demonstrates how to set standard delimiters like comma, semicolon, and pipe for CSV output.
```python
# Standard delimiters
Xlsx2csv("file.xlsx", delimiter=",") # Comma (default)
Xlsx2csv("file.xlsx", delimiter=";") # Semicolon
Xlsx2csv("file.xlsx", delimiter="|") # Pipe
```
--------------------------------
### Float Format Examples
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Shows how to control the precision of floating-point numbers in the output using printf-style codes.
```python
# Float formats (printf-style codes)
Xlsx2csv("file.xlsx", floatformat="%.2f") # 2 decimal places
Xlsx2csv("file.xlsx", floatformat="%.15f") # 15 decimal places
Xlsx2csv("file.xlsx", floatformat="%.0f") # No decimal places
```
--------------------------------
### Basic xlsx2csv Usage
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Use the installed xlsx2csv command-line tool for basic file conversion.
```bash
xlsx2csv input.xlsx output.csv
```
--------------------------------
### Special Delimiter Examples
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Shows how to use special characters and their ASCII codes as delimiters, including tab and file separator.
```python
# Special delimiters
Xlsx2csv("file.xlsx", delimiter="tab") # Tab character
Xlsx2csv("file.xlsx", delimiter="x09") # Tab (ASCII code)
Xlsx2csv("file.xlsx", delimiter="x1c") # File separator (ASCII 28)
Xlsx2csv("file.xlsx", delimiter="fs") # Field separator (ASCII 28)
```
--------------------------------
### Workbook Usage Example
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Workbook.md
Demonstrates how to access and use a Workbook object through an Xlsx2csv instance. Shows iteration over sheets, checking the date system, and converting specific or all sheets.
```python
from xlsx2csv import Xlsx2csv
with Xlsx2csv("myfile.xlsx") as converter:
workbook = converter.workbook
# Iterate over sheets
for sheet in workbook.sheets:
print(f"Sheet: {sheet['name']} (index {sheet['index']})")
if sheet['state'] == 'hidden':
print(" -> This sheet is hidden")
# Check date system
if workbook.date1904:
print("Workbook uses 1904 date system")
# Convert a specific sheet by index
converter.convert("output.csv", sheetid=1)
# Convert all sheets
converter.convert("output_dir", sheetid=0)
```
--------------------------------
### Example Error Output and Exit Code
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Demonstrates how an invalid XLSX file is handled, showing the error message printed to stderr and the non-zero exit code returned by the script.
```bash
python xlsx2csv.py bad_file.xlsx output.csv
Invalid xlsx file: bad_file.xlsx
$ echo $?
```
```bash
1
```
--------------------------------
### Convert All Sheets to Separate Files
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/README.md
This example shows how to convert all sheets in an Excel file into separate CSV files. The output will be saved to the specified directory.
```python
with Xlsx2csv("input.xlsx") as converter:
converter.convert("output_dir", sheetid=0)
```
--------------------------------
### Sheet Relationships XML Example (Hyperlinks)
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Relationships.md
This XML snippet illustrates a sheet-level relationships file, specifically mapping a relationship ID to an external hyperlink target.
```xml
```
--------------------------------
### Catch OutFileAlreadyExistsException
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/exceptions.md
Example of catching OutFileAlreadyExistsException when attempting to convert all sheets to an output path that is an existing file. This ensures the output path is correctly specified.
```python
from xlsx2csv import Xlsx2csv, OutFileAlreadyExistsException
try:
with Xlsx2csv("myfile.xlsx") as converter:
converter.convert("existing_file.csv", sheetid=0)
except OutFileAlreadyExistsException as e:
print(f"Output file exists: {e}")
```
--------------------------------
### Workbook Relationships XML Example
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Relationships.md
This XML snippet shows the structure of a typical workbook relationships file, mapping relationship IDs to targets like worksheets, styles, and shared strings.
```xml
```
--------------------------------
### Catch InvalidXlsxFileException
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/exceptions.md
Example of how to catch the InvalidXlsxFileException when attempting to convert an invalid XLSX file. This ensures graceful handling of malformed input files.
```python
from xlsx2csv import Xlsx2csv, InvalidXlsxFileException
try:
with Xlsx2csv("bad_file.xlsx") as converter:
converter.convert("output.csv")
except InvalidXlsxFileException as e:
print(f"Invalid XLSX: {e}")
```
--------------------------------
### Advanced Conversion: Hyperlinks, Merged Cells, Hidden Sheets
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Enable handling of hyperlinks, merged cells, and control the exclusion of hidden sheets and rows using specific boolean flags within a `with` statement. This example also specifies the output directory and sheet ID.
```python
# Advanced: hyperlinks, merged cells, exclude hidden sheets
with Xlsx2csv("file.xlsx",
hyperlinks=True,
merge_cells=True,
exclude_hidden_sheets=True,
skip_hidden_rows=True
) as converter:
converter.convert("output_dir", sheetid=0)
```
--------------------------------
### Basic Conversion using Context Manager
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Recommended way to use xlsx2csv for file conversion. Ensures resources are properly managed.
```python
from xlsx2csv import Xlsx2csv
with Xlsx2csv("myfile.xlsx", outputencoding="utf-8") as converter:
converter.convert("myfile.csv")
```
--------------------------------
### Optional arguments documentation
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
List of available flags to customize the conversion process.
```text
-h, --help show this help message and exit
-v, --version show program's version number and exit
-a, --all export all sheets
-c OUTPUTENCODING, --outputencoding OUTPUTENCODING
encoding of output CSV **Python 3 only** (default: utf-8)
-s SHEETID, --sheet SHEETID
sheet number to convert, 0 for all
-n SHEETNAME, --sheetname SHEETNAME
sheet name to convert
-d DELIMITER, --delimiter DELIMITER
delimiter - column delimiter in CSV, 'tab' or 'x09'
for a tab (default: comma ',')
-l LINETERMINATOR, --lineterminator LINETERMINATOR
line terminator - line terminator in CSV, '\n' '\r\n'
or '\r' (default: os.linesep)
-f DATEFORMAT, --dateformat DATEFORMAT
override date/time format (ex. %Y/%m/%d)
--floatformat FLOATFORMAT
override float format (ex. %.15f)
-i, --ignoreempty skip empty lines
-e, --escape escape \r\n\t characters
-p SHEETDELIMITER, --sheetdelimiter SHEETDELIMITER
sheet delimiter used to separate sheets, pass '' if
you do not need a delimiter, or 'x07' or '\\f' for form
feed (default: '--------')
-q QUOTING, --quoting QUOTING
field quoting, 'none' 'minimal' 'nonnumeric' or 'all' (default: 'minimal')
--hyperlinks, --hyperlinks
include hyperlinks
-I INCLUDE_SHEET_PATTERN [INCLUDE_SHEET_PATTERN ...], --include_sheet_pattern INCLUDE_SHEET_PATTERN [INCLUDE_SHEET_PATTERN ...]
only include sheets with names matching the given pattern, only
affects when -a option is enabled.
-E EXCLUDE_SHEET_PATTERN [EXCLUDE_SHEET_PATTERN ...], --exclude_sheet_pattern EXCLUDE_SHEET_PATTERN [EXCLUDE_SHEET_PATTERN ...]
exclude sheets with names matching the given pattern, only
affects when -a option is enabled.
-m, --merge-cells merge cells
```
--------------------------------
### Command-line usage syntax
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
General syntax for running the conversion script from the terminal.
```text
xlsx2csv.py [-h] [-v] [-a] [-c OUTPUTENCODING] [-s SHEETID]
[-n SHEETNAME] [-d DELIMITER] [-l LINETERMINATOR]
[-f DATEFORMAT] [--floatformat FLOATFORMAT]
[-i] [-e] [-p SHEETDELIMITER]
[--hyperlinks]
[-I INCLUDE_SHEET_PATTERN [INCLUDE_SHEET_PATTERN ...]]
[-E EXCLUDE_SHEET_PATTERN [EXCLUDE_SHEET_PATTERN ...]] [-m]
xlsxfile [outfile]
```
--------------------------------
### Get Sheet ID by Name
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Retrieves the 1-indexed ID of a sheet given its name. Returns None if the sheet is not found.
```python
with Xlsx2csv("myfile.xlsx") as converter:
sheet_id = converter.getSheetIdByName("DataSheet")
if sheet_id:
converter.convert("output.csv", sheetid=sheet_id)
```
--------------------------------
### Xlsx2csv Constructor and Context Manager
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Demonstrates how to initialize Xlsx2csv and use it as a context manager for file conversions. Allows for specifying output encoding, date formats, and options like skipping empty lines or merging cells.
```APIDOC
## Xlsx2csv Constructor and Context Manager
### Description
Initializes the Xlsx2csv converter. It can be used as a context manager (`with` statement) for automatic resource management. Various optional parameters can be provided during initialization to customize the conversion process.
### Parameters
- **`filename`** (str): Path to the input XLSX file.
- **`outputencoding`** (str, optional): Encoding for the output CSV file. Defaults to `utf-8`.
- **`dateformat`** (str, optional): Custom format for dates. Defaults to the system's default.
- **`skip_empty_lines`** (bool, optional): If True, empty lines in the XLSX will be skipped. Defaults to False.
- **`merge_cells`** (bool, optional): If True, merged cells will be handled. Defaults to False.
- **`sheetdelimiter`** (str, optional): A string to use as a delimiter between sheets when converting all sheets to a single file.
### Example Usage (Context Manager):
```python
from xlsx2csv import Xlsx2csv
# Basic conversion with specified encoding
with Xlsx2csv("myfile.xlsx", outputencoding="utf-8") as converter:
converter.convert("myfile.csv")
# Convert all sheets to separate files in a directory
with Xlsx2csv("myfile.xlsx") as converter:
converter.convert("output_dir", sheetid=0)
# Custom date format
with Xlsx2csv("myfile.xlsx", dateformat="%Y-%m-%d") as converter:
converter.convert("output.csv")
# Skip empty lines and merge cells
with Xlsx2csv("myfile.xlsx", skip_empty_lines=True, merge_cells=True) as converter:
converter.convert("output.csv")
```
```
--------------------------------
### Interpreting Sheet Definitions
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/types.md
Iterate through workbook sheets to get their index, name, and visibility state. This helps in understanding the structure of an Excel file.
```python
from xlsx2csv import Xlsx2csv
with Xlsx2csv("myfile.xlsx") as converter:
for sheet in converter.workbook.sheets:
visibility = "visible"
if sheet['state'] == 'hidden':
visibility = "hidden"
elif sheet['state'] == 'veryHidden':
visibility = "very hidden"
print(f"Sheet {sheet['index']}: {sheet['name']} ({visibility})")
```
--------------------------------
### Positional arguments documentation
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
Definitions for the required input and output file paths.
```text
xlsxfile xlsx file path, use '-' to read from STDIN
outfile output csv file path, or directory if -s 0 is specified
```
--------------------------------
### Command-Line Usage
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
This section details how to use the xlsx2csv script from the command line, including all available options.
```APIDOC
## xlsx2csv Command-Line Interface
### Description
Converts XLSX files to CSV format from the command line. Handles large files and offers various customization options.
### Usage
```sh
xlsx2csv.py [-h] [-v] [-a] [-c OUTPUTENCODING] [-s SHEETID] [-n SHEETNAME] [-d DELIMITER] [-l LINETERMINATOR] [-f DATEFORMAT] [--floatformat FLOATFORMAT] [-i] [-e] [-p SHEETDELIMITER] [--hyperlinks] [-I INCLUDE_SHEET_PATTERN [INCLUDE_SHEET_PATTERN ...]] [-E EXCLUDE_SHEET_PATTERN [EXCLUDE_SHEET_PATTERN ...]] [-m] xlsxfile [outfile]
```
### Arguments
#### Positional Arguments
- **xlsxfile** (string) - Required - Path to the XLSX file, use '-' to read from STDIN.
- **outfile** (string) - Optional - Path to the output CSV file, or directory if -s 0 is specified.
#### Optional Arguments
- **-h, --help** (boolean) - Show this help message and exit.
- **-v, --version** (boolean) - Show program's version number and exit.
- **-a, --all** (boolean) - Export all sheets.
- **-c OUTPUTENCODING, --outputencoding OUTPUTENCODING** (string) - Encoding of the output CSV. **Python 3 only** (default: 'utf-8').
- **-s SHEETID, --sheet SHEETID** (integer) - Sheet number to convert, 0 for all.
- **-n SHEETNAME, --sheetname SHEETNAME** (string) - Sheet name to convert.
- **-d DELIMITER, --delimiter DELIMITER** (string) - Column delimiter in CSV. Use 'tab' or 'x09' for a tab (default: ',').
- **-l LINETERMINATOR, --lineterminator LINETERMINATOR** (string) - Line terminator in CSV. Use '\n', '\r\n', or '\r' (default: os.linesep).
- **-f DATEFORMAT, --dateformat DATEFORMAT** (string) - Override date/time format (e.g., '%Y/%m/%d').
- **--floatformat FLOATFORMAT** (string) - Override float format (e.g., '%.15f').
- **-i, --ignoreempty** (boolean) - Skip empty lines.
- **-e, --escape** (boolean) - Escape \r\n\t characters.
- **-p SHEETDELIMITER, --sheetdelimiter SHEETDELIMITER** (string) - Sheet delimiter used to separate sheets. Pass '' for no delimiter, or 'x07' or '\f' for form feed (default: '--------').
- **-q QUOTING, --quoting QUOTING** (string) - Field quoting. Options: 'none', 'minimal', 'nonnumeric', 'all' (default: 'minimal').
- **--hyperlinks** (boolean) - Include hyperlinks.
- **-I INCLUDE_SHEET_PATTERN, --include_sheet_pattern INCLUDE_SHEET_PATTERN** (list of strings) - Only include sheets with names matching the given pattern. Only affects when -a option is enabled.
- **-E EXCLUDE_SHEET_PATTERN, --exclude_sheet_pattern EXCLUDE_SHEET_PATTERN** (list of strings) - Exclude sheets with names matching the given pattern. Only affects when -a option is enabled.
- **-m, --merge-cells** (boolean) - Merge cells.
### Examples
**Convert a single file:**
```sh
xlsx2csv.py input.xlsx output.csv
```
**Convert all sheets from a file to a directory:**
```sh
xlsx2csv.py input.xlsx output_dir/ -a
```
**Convert a directory of XLSX files:**
```sh
python xlsx2csv.py /path/to/input/dir /path/to/output/dir
```
```
--------------------------------
### Python Main Function Signature
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Defines the command-line entry point for the xlsx2csv converter. It parses arguments and initiates the conversion process.
```python
def main() -> None
```
--------------------------------
### Initialize SharedStrings Container
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/SharedStrings.md
Initializes an empty SharedStrings container. This is the constructor for the class.
```python
def __init__(self)
```
--------------------------------
### STANDARD_FORMATS Dictionary for Excel Format IDs
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/types.md
Maps Excel's built-in number format IDs to format code strings. Custom formats use IDs starting at 164.
```python
STANDARD_FORMATS: dict[int, str]
```
--------------------------------
### Xlsx2csv Initialization and ContentTypes Access
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/ContentTypes.md
Demonstrates how to initialize Xlsx2csv and access the discovered content types, including workbook, styles, and shared strings paths.
```python
from xlsx2csv import Xlsx2csv
with Xlsx2csv("myfile.xlsx") as converter:
# These paths were discovered via ContentTypes.parse()
content_types = converter.content_types
workbook_path = content_types.types["workbook"]
styles_path = content_types.types["styles"]
shared_strings_path = content_types.types["shared_strings"]
print(f"Workbook: {workbook_path}")
print(f"Styles: {styles_path}")
print(f"Shared Strings: {shared_strings_path}")
```
--------------------------------
### Initialize Xlsx2csv Converter
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Initialize the converter with an XLSX file path or a file-like object. Supports various options for customizing CSV output.
```python
def __init__(self, xlsxfile, **options)
```
--------------------------------
### Simple Library Usage
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/overview.md
Use the Xlsx2csv class as a context manager to convert a single XLSX file to a CSV file. Ensure the input XLSX file and output CSV file paths are correctly specified.
```python
from xlsx2csv import Xlsx2csv
# Simple usage
with Xlsx2csv("myfile.xlsx") as converter:
converter.convert("output.csv")
```
--------------------------------
### Run Comprehensive Test Suite
Source: https://github.com/dilshod/xlsx2csv/blob/master/CLAUDE.md
Execute the full test suite to verify XLSX to CSV conversion accuracy against expected outputs. This command is useful for ensuring the integrity of the converter, especially after code changes.
```bash
python3 test/run
```
--------------------------------
### Command-Line: Convert First Sheet
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/overview.md
Convert the first sheet of an XLSX file to a CSV file using the command-line interface. Specify input and output file paths.
```bash
# Convert first sheet
xlsx2csv input.xlsx output.csv
```
--------------------------------
### Initialize Styles Container
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Styles.md
Initializes an empty container for managing cell styles and number formats. This is typically done internally by the Xlsx2csv class.
```python
def __init__(self):
pass
```
--------------------------------
### Xlsx2csv Initialization and Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/overview.md
This snippet shows how to initialize the Xlsx2csv converter with a specific date format and then convert a sheet from an XLSX file to a CSV file. The constructor handles the initial parsing of workbook, styles, and shared strings.
```python
with Xlsx2csv("data.xlsx", dateformat="%Y-%m-%d") as converter:
# Constructor parses workbook, styles, shared strings
converter.convert("output.csv", sheetid=1)
```
--------------------------------
### Build Python Package
Source: https://github.com/dilshod/xlsx2csv/blob/master/CLAUDE.md
Build the Python package using the modern build system defined in pyproject.toml. This command is essential for creating distributable artifacts of the project.
```bash
python3 -m build
```
--------------------------------
### Data Preservation: Raw Values for Dates and Percentages
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Configure the converter to output raw values for dates (as Excel serial numbers) and percentages (as their decimal equivalents) using `dateformat="float"` and `ignore_percentage=True` respectively.
```python
# Data preservation: output raw values without formatting
with Xlsx2csv("file.xlsx",
dateformat="float", # Output dates as Excel serial numbers
ignore_percentage=True # Output 0.50 instead of 50%
) as converter:
converter.convert("output.csv")
```
--------------------------------
### Initialize Workbook
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Workbook.md
Initializes an empty Workbook object. This is typically called internally by the Xlsx2csv class.
```python
def __init__(self)
```
--------------------------------
### Default Application Path
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/types.md
The default application path prefix for XLSX metadata files. This is used for constructing fallback paths when metadata files cannot be discovered.
```python
DEFAULT_APP_PATH: str
"/xl"
```
--------------------------------
### Accessing Cell Styles
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Styles.md
Demonstrates how to access the styles object during XLSX conversion to retrieve format codes for cell styles.
```python
from xlsx2csv import Xlsx2csv
with Xlsx2csv("myfile.xlsx") as converter:
styles = converter.styles
# Get format code for cell style 5
format_id = styles.cellXfs[5]
format_code = styles.chk_exists(format_id)
print(f"Cell format: {format_code}")
```
--------------------------------
### Use as a Python library
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
Integrate conversion logic directly into Python scripts using the Xlsx2csv class.
```python
from xlsx2csv import Xlsx2csv
# Recommended: using context manager for proper resource cleanup
with Xlsx2csv("myfile.xlsx", outputencoding="utf-8") as xlsx2csv:
xlsx2csv.convert("myfile.csv")
# Simple usage (but may cause ResourceWarning in modern Python)
Xlsx2csv("myfile.xlsx", outputencoding="utf-8").convert("myfile.csv")
```
--------------------------------
### Recursive xlsx2csv Directory Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Use the -a flag with xlsx2csv to recursively convert all .xlsx files in a directory.
```bash
xlsx2csv -a input.xlsx output_dir
```
--------------------------------
### Convert directory of files
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
Batch convert all XLSX files in a directory to CSV.
```sh
python xlsx2csv.py /path/to/input/dir /path/to/output/dir
```
--------------------------------
### XLSX File Structure Overview
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/ContentTypes.md
This snippet illustrates the hierarchical organization of files within a standard XLSX archive, highlighting the location of critical metadata and content files.
```text
[Content_Types].xml ← Describes file types and locations
_rels/
.rels ← Relationships from root
xl/
workbook.xml ← Workbook metadata (discovered here)
workbook.xml.rels ← Relationships from workbook
styles.xml ← Cell formats (discovered here)
sharedStrings.xml ← Text strings (discovered here)
worksheets/
sheet1.xml ← First worksheet
sheet2.xml ← Second worksheet
_rels/
sheet1.xml.rels ← Hyperlinks, images, etc.
_rels/
workbook.xml.rels
sheet1.xml.rels
docProps/
core.xml
app.xml
```
--------------------------------
### Exclude Hidden Sheets During Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Workbook.md
Demonstrates how to initialize Xlsx2csv with the `exclude_hidden_sheets=True` option to automatically skip hidden sheets during conversion.
```python
with Xlsx2csv("myfile.xlsx", exclude_hidden_sheets=True) as converter:
# Only normal sheets are converted when using sheetid=0
converter.convert("output_dir", sheetid=0)
```
--------------------------------
### Python API Usage
Source: https://github.com/dilshod/xlsx2csv/blob/master/README.md
This section demonstrates how to use the xlsx2csv library within a Python script.
```APIDOC
## xlsx2csv Python API
### Description
Integrate xlsx2csv functionality directly into your Python applications.
### Usage
**Recommended: Using context manager for proper resource cleanup**
```python
from xlsx2csv import Xlsx2csv
with Xlsx2csv("myfile.xlsx", outputencoding="utf-8") as xlsx2csv:
xlsx2csv.convert("myfile.csv")
```
**Simple usage (may cause ResourceWarning in modern Python)**
```python
from xlsx2csv import Xlsx2csv
Xlsx2csv("myfile.xlsx", outputencoding="utf-8").convert("myfile.csv")
```
### Class: `Xlsx2csv`
#### Constructor
`Xlsx2csv(xlsxfile, outputencoding='utf-8', ...)`
- **xlsxfile** (string) - Path to the XLSX file.
- **outputencoding** (string) - Encoding for the output CSV file (default: 'utf-8').
- Other optional arguments correspond to the command-line options (e.g., `sheet`, `delimiter`, `lineterminator`, etc.).
#### Method: `convert(outfile)`
- **outfile** (string) - Path to the output CSV file.
Converts the specified XLSX file to CSV format and saves it to the `outfile` path.
```
--------------------------------
### Include Hyperlinks and Merge Cells
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Converts an XLSX file, including hyperlink information and merging cell values. Uses the `--hyperlinks` and `-m` flags.
```bash
python xlsx2csv.py --hyperlinks -m input.xlsx output.csv
```
--------------------------------
### Skip Empty Lines and Trailing Columns
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Converts an XLSX file while skipping empty lines and trailing empty columns. Uses the `-i` and `--skipemptycolumns` flags.
```bash
python xlsx2csv.py -i --skipemptycolumns input.xlsx output.csv
```
--------------------------------
### Sheet Constructor
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Sheet.md
Initializes a Sheet parser with necessary workbook, shared string, styles, and file handle information. This is an internal method, typically not called directly by users.
```python
def __init__(self, workbook, sharedString, styles, filehandle)
```
--------------------------------
### Clean Output Configuration
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Use `skip_empty_lines=True`, `skip_trailing_columns=True`, and `no_line_breaks=True` within a `with` statement to produce clean CSV output by removing empty lines, trailing columns, and replacing line breaks.
```python
# Clean output: no empty lines, no trailing columns, no line breaks
with Xlsx2csv("file.xlsx",
skip_empty_lines=True,
skip_trailing_columns=True,
no_line_breaks=True
) as converter:
converter.convert("output.csv")
```
--------------------------------
### Access Relationship Metadata
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Relationships.md
Demonstrates how to access the metadata for a specific relationship ID from the `relationships` attribute. The metadata includes the relationship type and its target path or URL.
```python
relationships.relationships["rId1"]
# {
# "type": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
# "target": "worksheets/sheet1.xml"
# }
```
--------------------------------
### Process Large XLSX Files with SAX Streaming
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/SharedStrings.md
Illustrates processing large XLSX files with numerous unique strings using SAX streaming for memory efficiency. It prints the number of shared strings loaded and then converts the file.
```python
import sys
# Large file with 100,000+ unique strings
with Xlsx2csv("large_file.xlsx") as converter:
print(f"Shared strings loaded: {len(converter.shared_strings.strings)}")
converter.convert("output.csv")
```
--------------------------------
### Convert Specific Sheet by Name
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Converts a single sheet identified by its name to a CSV file. Use the `-n` option followed by the sheet name.
```bash
python xlsx2csv.py -n "DataSheet" input.xlsx output.csv
```
--------------------------------
### Convert Directory of XLSX Files
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Converts all XLSX files within a specified input directory to CSV files in an output directory. Both input and output paths are directories.
```bash
python xlsx2csv.py /path/to/xlsx/dir /path/to/output/dir
```
--------------------------------
### Accessing Workbook and Sheet Metadata
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Use this snippet to iterate through the sheets of an XLSX file and print their names, indices, and states. The context manager pattern is recommended for proper resource cleanup.
```python
with Xlsx2csv("myfile.xlsx") as converter:
for sheet in converter.workbook.sheets:
print(f"Sheet: {sheet['name']} (index {sheet['index']}, state: {sheet['state']})")
```
--------------------------------
### Set Time Format
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Sheet.md
Override the default time format using strftime codes. Defaults to "%H:%M".
```python
sheet.set_timeformat("%H:%M:%S") # Include seconds
```
--------------------------------
### Convert All Sheets to File with Delimiters
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Converts all sheets in an Excel file and writes them to a single output file, using a specified delimiter between sheets.
```python
with open("output.csv", "w") as f:
with Xlsx2csv("myfile.xlsx", sheetdelimiter="---") as converter:
converter.convert(f, sheetid=0)
```
--------------------------------
### Batch Processing with Error Recovery
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/exceptions.md
Illustrates how to process multiple XLSX files in a batch, with error recovery for each file. This pattern allows the process to continue even if some files fail to convert.
```python
from xlsx2csv import Xlsx2csv, XlsxException
import os
xlsx_files = ["file1.xlsx", "file2.xlsx", "file3.xlsx"]
for xlsx_path in xlsx_files:
output_path = xlsx_path.replace(".xlsx", ".csv")
try:
with Xlsx2csv(xlsx_path) as converter:
converter.convert(output_path)
print(f"✓ Converted {xlsx_path}")
except XlsxException as e:
print(f"✗ Failed {xlsx_path}: {e}")
```
--------------------------------
### Xlsx2csv.md - Main Converter Class API
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/README.md
API reference for the main Xlsx2csv converter class, detailing its methods, parameters, and return types for converting XLSX files to CSV.
```APIDOC
## Xlsx2csv Class API
This section provides the API documentation for the main `Xlsx2csv` converter class.
### Class Signature
```python
class Xlsx2csv:
# ... methods and attributes ...
```
### Methods
#### `convert(self, xlsx_file, csv_file, options=None)`
##### Description
Converts an XLSX file to a CSV file.
##### Parameters
- **xlsx_file** (str) - Required - Path to the input XLSX file.
- **csv_file** (str) - Required - Path to the output CSV file.
- **options** (dict) - Optional - A dictionary of configuration options.
##### Return Type
- None
### Configuration Options
Refer to [configuration.md](configuration.md) for a complete list of configuration options that can be passed in the `options` dictionary.
```
--------------------------------
### Detecting Date, Time, and Percentage Formats
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Styles.md
This snippet demonstrates how format codes are analyzed to infer whether a cell's value is a date, time, or percentage. It checks for common characters associated with each format type.
```python
format_code = "yyyy-mm-dd"
if "y" in format_code or "m" in format_code or "d" in format_code:
# Likely a date format
format_type = "date"
elif "h" in format_code or "s" in format_code:
# Likely a time format
format_type = "time"
elif "%" in format_code:
# Percentage format
format_type = "percentage"
```
--------------------------------
### Export with Specific Formatting Options
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/overview.md
Customize the CSV output by specifying delimiter, date format, float format, and options to skip empty lines or trailing columns during conversion.
```python
with Xlsx2csv("report.xlsx",
delimiter=";",
dateformat="%d.%m.%Y",
floatformat="%.2f",
skip_empty_lines=True,
skip_trailing_columns=True
) as converter:
converter.convert("report.csv")
```
--------------------------------
### Custom Formatting for Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/README.md
Customize the conversion process by specifying date formats, delimiters, and options to skip empty lines. This allows for tailored CSV output.
```python
with Xlsx2csv("input.xlsx",
dateformat="%Y-%m-%d",
delimiter=";",
skip_empty_lines=True
) as converter:
converter.convert("output.csv")
```
--------------------------------
### Skip All Formatting
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
To output all cells with their raw values, bypassing any formatting like dates, times, or floats, provide a list of all format types to `ignore_formats`.
```python
# Skip all formatting
Xlsx2csv("file.xlsx", ignore_formats=['date', 'time', 'float', 'percentage']).convert("output.csv")
# All cells output raw values
```
--------------------------------
### Access Shared Strings by Index
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/SharedStrings.md
Demonstrates how to access the shared strings table and retrieve a specific string by its index. This is typically done after initializing Xlsx2csv.
```python
from xlsx2csv import Xlsx2csv
with Xlsx2csv("myfile.xlsx") as converter:
shared_strings = converter.shared_strings
# Access a specific string by index
string_value = shared_strings.strings[0] # First string
# Total string count
print(f"Total unique strings: {len(shared_strings.strings)}")
```
--------------------------------
### Instance Method: convert
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Converts a specified sheet or all sheets from an XLSX file to CSV format. Output can be a file path, a file-like object, or a directory for multi-sheet conversion.
```APIDOC
## `convert(outfile, sheetid=1, sheetname=None)`
### Description
Converts a sheet or multiple sheets from the XLSX file to CSV format. The output can be directed to a file path, a file-like object, or a directory if converting all sheets.
### Method
`convert`
### Parameters
- **`outfile`** (str or file-like (`TextIO`)): Required. Output file path, or file handle opened in write mode. If `sheetid=0`, this must be a directory path or a file-like object supporting sheet delimiters.
- **`sheetid`** (int): Optional. Sheet number (1-indexed). Use `0` to convert all sheets. Defaults to `1`.
- **`sheetname`** (str): Optional. Convert the sheet with this name instead of using `sheetid`. Takes precedence over `sheetid` if both are provided.
### Raises
- `SheetNotFoundException`: if `sheetid` or `sheetname` is not found.
- `OutFileAlreadyExistsException`: if converting all sheets and the output directory already exists as a file.
- `XlsxException`: on other conversion errors.
### Examples:
```python
# Convert sheet 1
with Xlsx2csv("myfile.xlsx") as converter:
converter.convert("output.csv", sheetid=1)
# Convert sheet by name
with Xlsx2csv("myfile.xlsx") as converter:
converter.convert("output.csv", sheetname="Sheet2")
# Convert all sheets to separate CSV files in a directory
with Xlsx2csv("myfile.xlsx") as converter:
converter.convert("output_dir", sheetid=0)
# Convert all sheets and write to a single file with delimiters between sheets
with open("output.csv", "w") as f:
with Xlsx2csv("myfile.xlsx", sheetdelimiter="---") as converter:
converter.convert(f, sheetid=0)
```
```
--------------------------------
### Error Handling with XlsxException
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/INDEX.md
Implement try-except blocks to catch potential `XlsxException` errors during file processing. This allows for graceful handling of issues like invalid file formats or missing sheets.
```python
try:
...
except XlsxException as e:
...
```
--------------------------------
### Basic xlsx2csv Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Converts a single XLSX file to a CSV file. This is the most basic usage of the script.
```bash
python xlsx2csv.py input.xlsx output.csv
```
--------------------------------
### Default Workbook Path
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/types.md
The default path to the workbook metadata file. This serves as a fallback when the workbook path is not found in the [Content_Types].xml file.
```python
DEFAULT_WORKBOOK_PATH: str
"/xl/workbook.xml"
```
--------------------------------
### Catch All XLSX Errors
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/exceptions.md
A general approach to catching any XlsxException during conversion. This is useful for broad error handling when specific error types do not need to be differentiated.
```python
from xlsx2csv import Xlsx2csv, XlsxException
try:
with Xlsx2csv("input.xlsx") as converter:
converter.convert("output.csv")
except XlsxException as e:
print(f"XLSX conversion failed: {e}")
```
--------------------------------
### European Format with Tab Delimiter and Custom Date Format
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Configure the converter for European number formatting, use a semicolon as a delimiter, and specify a DD/MM/YYYY date format using a `with` statement for context management.
```python
# European format with tab delimiter and DD/MM/YYYY dates
with Xlsx2csv("file.xlsx",
delimiter=";",
dateformat="%d/%m/%Y",
floatformat="%.2f"
) as converter:
converter.convert("output.csv")
```
--------------------------------
### Filter Visible Sheets
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Workbook.md
Shows how to filter sheets to retrieve only those that are visible (state is None).
```python
with Xlsx2csv("myfile.xlsx") as converter:
# Get visible sheets only
visible_sheets = [s for s in converter.workbook.sheets if s['state'] is None]
```
--------------------------------
### Read from Standard Input
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Reads XLSX data from standard input (STDIN) and converts it to a CSV file. This is useful for piping data from other commands. Requires Python 3.
```bash
cat input.xlsx | python xlsx2csv.py - output.csv
```
--------------------------------
### Include Hyperlinks Option
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/INDEX.md
Activate the `hyperlinks` option to include hyperlink information in the converted CSV output. This option is configured when creating an Xlsx2csv instance.
```python
Xlsx2csv("file.xlsx", hyperlinks=True)
```
--------------------------------
### Include Sheets by Pattern
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/configuration.md
Converts only the sheets whose names match a given regular expression pattern. Requires sheetid=0 to process multiple sheets.
```python
# Include/exclude sheets by pattern (with sheetid=0)
Xlsx2csv("file.xlsx", include_sheet_pattern=["Data.*"])
# Only sheets matching /Data.*/
```
--------------------------------
### Skip Empty Lines and Merge Cells
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Configures the converter to ignore empty lines and merge adjacent cells with the same content.
```python
with Xlsx2csv("myfile.xlsx", skip_empty_lines=True, merge_cells=True) as converter:
converter.convert("output.csv")
```
--------------------------------
### Instance Method: close
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Explicitly closes the underlying file handle for the XLSX file. This is automatically handled by the context manager but can be called manually for explicit cleanup.
```APIDOC
## `close()`
### Description
Explicitly closes the underlying ZIP file handle used to access the XLSX file. This method is automatically called when the `Xlsx2csv` object is used within a `with` statement (context manager) or when the object is garbage collected. Manual invocation is useful for ensuring resources are released promptly.
### Method
`close`
### Returns
- `None`
### Example:
```python
# Using the converter without a context manager
converter = Xlsx2csv("myfile.xlsx")
try:
converter.convert("output.csv")
finally:
converter.close() # Explicit cleanup to avoid ResourceWarning
```
```
--------------------------------
### Preserve Raw Values During Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/overview.md
Configure the converter to preserve raw numerical and date values. Use 'float' for dateformat to keep Excel serial numbers and ignore_percentage to treat percentages as decimals. 'ignore_formats' can be used to keep numbers as-is.
```python
with Xlsx2csv("data.xlsx",
dateformat="float", # Dates as Excel serial numbers
ignore_percentage=True, # Percentages as decimals
ignore_formats=['float'] # Numbers as-is
) as converter:
converter.convert("data.csv")
```
--------------------------------
### Custom Date Format Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Converts an XLSX file while applying a custom date format. Use the `-f` option with the desired format string.
```bash
python xlsx2csv.py -f "%d/%m/%Y" input.xlsx output.csv
```
--------------------------------
### set_ignore_percentage
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Sheet.md
Configures whether to ignore percentage formatting and output raw decimal values.
```APIDOC
## set_ignore_percentage(ignore_percentage)
### Description
Ignore percentage formatting and output raw decimal values.
### Parameters
#### Path Parameters
- **ignore_percentage** (bool) - Required - If True, cells formatted as percentage output as decimal (e.g., `0.50` instead of `50%`).
```
--------------------------------
### Set Skip Empty Lines
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Sheet.md
Configure whether to skip rows where all cells are empty. If True, these rows are not written to CSV.
```python
sheet.set_skip_empty_lines(True)
```
--------------------------------
### Custom Date Format Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Xlsx2csv.md
Allows specifying a custom date format for values during conversion.
```python
with Xlsx2csv("myfile.xlsx", dateformat="%Y-%m-%d") as converter:
converter.convert("output.csv")
```
--------------------------------
### Retrieve Cell Format ID and Code
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Styles.md
Shows how to retrieve the number format ID for a given cell style ID and then look up the corresponding format code. It checks both custom formats in `numFmts` and built-in formats in `STANDARD_FORMATS`.
```python
s_attr = 5 # Cell has style ID 5
format_id = styles.cellXfs[5] # Retrieve format ID
format_code = styles.numFmts.get(format_id) or STANDARD_FORMATS.get(format_id)
```
--------------------------------
### Set No Line Breaks
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Sheet.md
Configure whether to replace newline and tab characters with spaces instead of preserving them. If True, '\r', '\n', '\t' are replaced with a space.
```python
sheet.set_no_line_breaks(True)
```
--------------------------------
### Batch Processing with convert_recursive
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/INDEX.md
Utilize the `convert_recursive` function for batch conversion of XLSX files within a directory. Specify input and output directories, and optionally pass keyword arguments for conversion options.
```python
convert_recursive("in_dir", 0, "out_dir", kwargs)
```
--------------------------------
### Differentiate XLSX Error Types
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/exceptions.md
Demonstrates how to differentiate between various specific XlsxException types in a single try-except block. This allows for tailored error messages and handling based on the nature of the exception.
```python
from xlsx2csv import (
Xlsx2csv,
InvalidXlsxFileException,
SheetNotFoundException,
OutFileAlreadyExistsException,
XlsxValueError
)
try:
with Xlsx2csv("input.xlsx") as converter:
converter.convert("output.csv", sheetid=5)
except InvalidXlsxFileException:
print("File is not a valid XLSX")
except SheetNotFoundException:
print("Sheet not found")
except OutFileAlreadyExistsException:
print("Output directory already exists")
except XlsxValueError:
print("Cell data formatting error")
```
--------------------------------
### Catch SheetNotFoundException
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/exceptions.md
Demonstrates how to catch SheetNotFoundException when a specified sheet index or name is not found in the XLSX file. This is useful for validating sheet existence before processing.
```python
from xlsx2csv import Xlsx2csv, SheetNotFoundException
try:
with Xlsx2csv("myfile.xlsx") as converter:
converter.convert("output.csv", sheetid=10)
except SheetNotFoundException as e:
print(f"Sheet not found: {e}")
```
--------------------------------
### Command-Line: Custom Date Format
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/overview.md
Specify a custom date format for the conversion using the `-f` flag. This ensures dates in the output CSV match the desired pattern.
```bash
# Custom date format
xlsx2csv -f "%d/%m/%Y" input.xlsx output.csv
```
--------------------------------
### Convert All Sheets to Separate Files
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/utility-functions.md
Exports all sheets from an XLSX file into individual CSV files within a specified output directory. Requires the `-a` flag.
```bash
python xlsx2csv.py -a input.xlsx output_dir
```
--------------------------------
### Custom Date Format Conversion
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/INDEX.md
Configure the date format for conversions by passing the `dateformat` argument to the Xlsx2csv constructor. This ensures dates are written in the desired string format.
```python
Xlsx2csv("file.xlsx", dateformat="%Y-%m-%d")
```
--------------------------------
### set_no_line_breaks
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/Sheet.md
Configures whether to replace newline and tab characters with spaces instead of preserving them.
```APIDOC
## set_no_line_breaks(no_line_breaks)
### Description
Replace newline and tab characters with spaces instead of preserving them.
### Parameters
#### Path Parameters
- **no_line_breaks** (bool) - Required - If True, `\r`, `\n`, `\t` are replaced with space.
```
--------------------------------
### Batch Process Directory of Excel Files
Source: https://github.com/dilshod/xlsx2csv/blob/master/_autodocs/overview.md
Recursively convert all Excel files in a directory to CSV. This function allows specifying output directory, sheet ID, custom conversion arguments (like delimiter and date format), and error handling behavior.
```python
from xlsx2csv import convert_recursive
convert_recursive(
path="/incoming",
sheetid=0,
outfile="/converted",
kwargs={'delimiter': ',', 'dateformat': '%Y-%m-%d'},
continue_on_error=True
)
```