### Write XLSX Files with fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/getting_started.md Demonstrates how to create and write data to XLSX files using the WriteOnlyWorkbook and WriteOnlyWorksheet classes. Supports various data types including strings, booleans, datetimes, numbers, and matrices. Includes an example for writing multiple files concurrently using `write_many`. ```python import datetime import numpy as np from fastxlsx import DType, WriteOnlyWorkbook, WriteOnlyWorksheet, write_many # Initialize workbook wb = WriteOnlyWorkbook() ws = wb.create_sheet("sheet1") ws.write_cell((0, 0), "Hello World!") ws.write_cell((1, 0), True, dtype=DType.Bool) ws.write_cell("B1", datetime.datetime.now(), dtype=DType.DateTime) ws.write_row((4, 2), ["var_a", "var_b", "var_c"], dtype=DType.Str) ws.write_column((4, 0), [2.5, "xyz", datetime.date.today()], dtype=DType.Any) # If `dtype` is one of [DType.Bool, DType.Int, DType.Float], must pass a numpy array ws.write_matrix((5, 2), np.random.random((3, 3)), dtype=DType.Float) # Save to file wb.save("./example.xlsx") # Write multiple files in parallel workbooks_to_write = {} for i_workbook in range(10): ws_list = [] for i_sheet in range(6): ws = WriteOnlyWorksheet(f"Sheet{i_sheet}") ws.write_cell("A1", 10 * i_workbook + i_sheet, dtype=DType.Int) ws.write_matrix((1, 1), np.random.random((3, 3)), dtype=DType.Float) ws_list.append(ws) workbooks_to_write[f"example_{i_workbook:02d}.xlsx"] = ws_list write_many(workbooks_to_write) ``` -------------------------------- ### Install FastXLSX using pip Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/index.md Installs the FastXLSX library from PyPI using the pip package manager. This is the simplest way to get started if you have Python and pip configured. ```bash pip install fastxlsx ``` -------------------------------- ### Read XLSX Files with fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/getting_started.md Shows how to read data from XLSX files using the ReadOnlyWorkbook class. Covers loading files, accessing sheets by index or name, reading individual cells, columns, and matrices using `RangeInfo` and `DShape`. Demonstrates reading multiple sheets and parallel reading of multiple files with `read_many`. ```python from fastxlsx import DShape, DType, RangeInfo, ReadOnlyWorkbook, read_many # Load xlsx file wb = ReadOnlyWorkbook("./example.xlsx") # List all sheet names print(wb.sheetnames) # Get a worksheet by index or name ws = wb.get_by_idx(0) # Read a single cell, notice the index is 0-based print(ws.cell_value((0, 0))) print(ws.cell_value("B1", dtype=DType.DateTime)) # Read a column with `read_value` and `RangeInfo` print(ws.read_value(RangeInfo((4, 0), DShape.Column(3), dtype=DType.Any))) print( ws.read_values( { "var_a": RangeInfo((5, 2), DShape.Column(3), dtype=DType.Float), "matrix": RangeInfo((5, 2), DShape.Matrix(3, 3), dtype=DType.Float), } ) ) # Read multiple sheets print(wb.read_worksheets({"sheet1": [RangeInfo((2, 2), DShape.Scalar())]})) # Read multiple files in parallel print( read_many( { f"./example_{i_workbook:02d}.xlsx": { f"Sheet{i_sheet}": [ RangeInfo((0, 0), DShape.Scalar()), RangeInfo((1, 1), DShape.Matrix(3, 3)), ] for i_sheet in range(6) } for i_workbook in range(10) } ) ) ``` -------------------------------- ### Build FastXLSX from Source Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/index.md Builds the FastXLSX library from its source code. This method requires cloning the repository and having a Rust toolchain installed for compilation. ```bash git clone https://github.com/shuangluoxss/fastxlsx.git cd fastxlsx pip install . ``` -------------------------------- ### Performance Optimization for Writing and Reading Excel Data Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt This example highlights performance optimizations for both writing and reading Excel data using `fastxlsx`. It compares the speed of auto-detection versus explicit data type declarations, demonstrating significant speedups, especially when using NumPy arrays for large datasets. ```python from fastxlsx import WriteOnlyWorkbook, ReadOnlyWorkbook, RangeInfo, DShape, DType import numpy as np import time # WRITING OPTIMIZATION wb = WriteOnlyWorkbook() ws = wb.create_sheet("Performance") # SLOW: Auto-detection (~0.3μs/cell overhead) start = time.time() ws.write_row((0, 0), [1, 2, 3, 4, 5]) # dtype not specified slow_time = time.time() - start # FAST: Explicit dtype with NumPy array start = time.time() ws.write_row((1, 0), np.array([1, 2, 3, 4, 5], dtype=np.int64), dtype=DType.Int) fast_time = time.time() - start print(f"Speedup: {slow_time/fast_time:.2f}x") # FASTEST: Large matrices with explicit types large_matrix = np.random.randn(10000, 100) start = time.time() ws.write_matrix((10, 0), large_matrix, dtype=DType.Float) matrix_time = time.time() - start print(f"Matrix write: {matrix_time:.3f}s, {large_matrix.size/matrix_time:.0f} cells/sec") wb.save("performance_test.xlsx") # READING OPTIMIZATION rb = ReadOnlyWorkbook("performance_test.xlsx") rs = rb.get(0) # SLOW: Auto-detect types (DType.Any) start = time.time() data_slow = rs.read_value(RangeInfo((10, 0), DShape.Matrix(10000, 100))) slow_read = time.time() - start # FAST: Explicit type returns NumPy array start = time.time() data_fast = rs.read_value( RangeInfo((10, 0), DShape.Matrix(10000, 100), dtype=DType.Float) ) fast_read = time.time() - start print(f"Read speedup: {slow_read/fast_read:.2f}x") print(f"Return type: {type(data_fast)}") # ``` -------------------------------- ### Creating Multiple Worksheets with fastxlsx Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Organize data across multiple sheets within a single workbook using `WriteOnlyWorkbook`. Each sheet can be created using `create_sheet` and accessed by name or index. This example demonstrates writing different types of data to separate sheets. ```python from fastxlsx import WriteOnlyWorkbook, DType import numpy as np wb = WriteOnlyWorkbook() # Create first sheet summary = wb.create_sheet("Summary") summary.write_cell("A1", "Q4 Summary Report") summary.write_row((2, 0), ["Metric", "Value"], dtype=DType.Str) summary.write_column((3, 0), ["Revenue", "Expenses", "Profit"], dtype=DType.Str) summary.write_column((3, 1), np.array([500000.0, 325000.0, 175000.0]), dtype=DType.Float) # Create second sheet details = wb.create_sheet("Details") details.write_matrix((0, 0), np.random.random((1000, 20)), dtype=DType.Float) # Create third sheet metadata = wb.create_sheet("Metadata") metadata.write_cell((0, 0), "Generated", dtype=DType.Str) metadata.write_cell((0, 1), datetime.datetime.now(), dtype=DType.DateTime) # Access sheets by name or index sheet1 = wb.get_by_name("Summary") sheet2 = wb.get_by_idx(1) sheet3 = wb.get("Details") # Works with name or index # List all sheet names print(wb.sheetnames()) # ["Summary", "Details", "Metadata"] wb.save("multi_sheet_report.xlsx") ``` -------------------------------- ### Retrieve Worksheet by Index in fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Retrieves a worksheet from the workbook using its 0-based index. This is a specialized version of the get method. Returns a WriteOnlyWorksheet object. ```python def get_by_idx(idx: int) -> WriteOnlyWorksheet: """Get a worksheet by its index.""" pass ``` -------------------------------- ### Writing Numerical Data with FastXLSX in Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/advanced_usage.md Illustrates the correct way to write numerical data using FastXLSX's `write_row` method. It shows a valid example using a NumPy array with a matching dtype and highlights an invalid case that raises a TypeError when using a Python list. ```python import numpy as np # Valid: NumPy array with matching dtype ws.write_row((1,0), np.array([4,5,6]), dtype=DType.Int) # Invalid: Python list with numerical dtype ws.write_row((2,0), [7,8,9], dtype=DType.Int) # Raises TypeError ``` -------------------------------- ### Write Column Data in fastxlsx.WriteOnlyWorksheet Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Writes a sequence of values as a column starting from a specified cell address. Accepts data as a NumPy array or a list. Optional data type enforcement is available. ```python def write_column(cell_addr: Union[Tuple[int, int], str], value: Union[np.ndarray, List[Any]], *, dtype=None) -> None: """Write a column of values starting from a specific cell.""" pass ``` -------------------------------- ### Retrieve Worksheet by Name in fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Retrieves a worksheet from the workbook using its title string. This is a specialized version of the get method. Returns a WriteOnlyWorksheet object. ```python def get_by_name(name: str) -> WriteOnlyWorksheet: """Get a worksheet by its name.""" pass ``` -------------------------------- ### Get Library Version - Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Retrieves the current version number of the fastxlsx library. This function is a simple utility and does not require any parameters or return complex data. ```python from fastxlsx import version current_version = version() print(f"fastxlsx version: {current_version}") ``` -------------------------------- ### Get Sheet Names in fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Returns a list containing the names of all worksheets currently present in the workbook. This is useful for iterating or referencing sheets. ```python def sheetnames() -> List[str]: """Get the names of all worksheets in the workbook.""" pass ``` -------------------------------- ### Strict Type Checking for Data Integrity in Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/advanced_usage.md Provides an example of FastXLSX's strict type checking mode. It demonstrates how a `ValueError` is raised when attempting to read data with an incorrect specified dtype, ensuring data integrity. ```python try: ws.read_value( RangeInfo((0,0), DShape.Row(3), dtype=DType.Str) ) except ValueError as e: print(f"Data integrity violation: {e}") ``` -------------------------------- ### Write Row Data in fastxlsx.WriteOnlyWorksheet Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Writes a sequence of values as a row starting from a specified cell address. Accepts data as a NumPy array or a list. Optional data type enforcement is available. ```python def write_row(cell_addr: Union[Tuple[int, int], str], value: Union[np.ndarray, List[Any]], *, dtype=None) -> None: """Write a row of values starting from a specific cell.""" pass ``` -------------------------------- ### fastxlsx.RangeInfo Class Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Class to describe a range of data within an XLSX file. It specifies the starting position, shape, data type, and strictness for reading or writing. ```APIDOC ## fastxlsx.RangeInfo(pos, data_shape=Ellipsis, *, dtype=Ellipsis, strict=True) ### Description Class to describe the range of data. ### Parameters - **pos** (tuple) - The starting position of the range as (row, col). - **data_shape** (DShape, optional) - Describes the shape of the data within the range. Defaults to Ellipsis. - **dtype** (DType, optional) - The expected data type of the values in the range. Defaults to Ellipsis. - **strict** (bool, optional) - Whether to enforce strict type checking. Defaults to True. ### Attributes - **data_shape** - The shape of the data. - **dtype** - The data type. - **end** (tuple) - The 0-based ending position of the range as (row, col). - **pos** (tuple) - The starting position of the range as (row, col). - **shape** (tuple) - The shape of the range as (n_rows, n_cols). - **start** (tuple) - The 0-based starting position of the range as (row, col). - **strict** (bool) - Strict type checking flag. ``` -------------------------------- ### Write Matrix Data in fastxlsx.WriteOnlyWorksheet Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Writes a 2D array or list of lists as a matrix starting from a specified cell address. Supports NumPy arrays or nested lists. Optional data type enforcement can be applied. ```python def write_matrix(cell_addr: Union[Tuple[int, int], str], value: Union[np.ndarray, List[List[Any]]], *, dtype=None) -> None: """Write a matrix of values starting from a specific cell.""" pass ``` -------------------------------- ### fastxlsx.ReadOnlyWorkbook Class Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Read-only workbook class for accessing data from existing XLSX files. Provides methods to get worksheets and read data from specified ranges. ```APIDOC ## fastxlsx.ReadOnlyWorkbook(path) ### Description Read-only workbook class. ### Parameters - **path** (str) - The path to the XLSX file. ### Methods #### get(idx_or_name) Get the sheet by index or name. - **Parameters**: - **idx_or_name** (Union[int, str]) - The 0-based index or name of the sheet. - **Returns**: [ReadOnlyWorksheet](#fastxlsx.ReadOnlyWorksheet) #### get_by_idx(idx) Get the sheet by index. - **Parameters**: - **idx** (int) - The 0-based index of the sheet. - **Returns**: [ReadOnlyWorksheet](#fastxlsx.ReadOnlyWorksheet) #### get_by_name(sheet_name) Get the sheet by sheet name. - **Parameters**: - **name** (str) - The name of the sheet. - **Returns**: [ReadOnlyWorksheet](#fastxlsx.ReadOnlyWorksheet) #### read_worksheets(worksheets_to_read) Read values from multiple worksheets based on specified ranges. - **Parameters**: - **worksheets_to_read** (Dict[Union[str, int], Union[List[RangeInfo], Dict[str, RangeInfo]]]) - A dictionary mapping worksheet identifiers to a list or dict of RangeInfo objects. - **Returns**: A dictionary mapping worksheet identifiers to the data read from the specified ranges. - **Return type**: Dict[Union[str, int], Union[List[Any], Dict[str, Any]]] ### Attributes - **n_sheets** (int) - The number of sheets in the workbook. - **path** (str) - The path to the XLSX file. - **sheetnames** (List[str]) - A list of sheet names in the workbook. - **worksheets** (List[ReadOnlyWorksheet]) - A list of all worksheet objects in the workbook. ``` -------------------------------- ### Read Single Cell Value in Python Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Demonstrates how to read individual cell values from an Excel worksheet using FastXLSX. Supports 0-based indexing or Excel-style cell addresses. Includes examples for type enforcement (strict and lenient modes) and handling data type mismatches. ```python from fastxlsx import ReadOnlyWorkbook, DType wb = ReadOnlyWorkbook("data.xlsx") ws = wb.get_by_idx(0) # Read cell using tuple notation (0-based) value1 = ws.cell_value((0, 0)) # Returns: "Hello World!" # Read cell using Excel address notation value2 = ws.cell_value("B1", dtype=DType.DateTime) # Returns: datetime.datetime(2025, 12, 2, 15, 30, 0) # Read with type enforcement try: value3 = ws.cell_value("C1", dtype=DType.Int, strict=True) except ValueError as e: print(f"Type mismatch: {e}") # Lenient mode - returns default on type mismatch value4 = ws.cell_value("D1", dtype=DType.Float, strict=False) # Returns: nan (if cell contains non-float data) ``` -------------------------------- ### Generate Multiple Workbooks and Sheets Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt This snippet demonstrates how to generate a large number of workbooks, each containing multiple sheets with headers, random data matrices, and metadata. It utilizes the `WriteOnlyWorksheet` and `write_many` functions for efficient batch processing. ```python from fastxlsx import WriteOnlyWorksheet, DType import numpy as np import datetime workbooks_to_write = {} # Generate 100 workbooks, each with 6 sheets for workbook_id in range(100): sheets = [] for sheet_id in range(6): ws = WriteOnlyWorksheet(f"Dataset_{sheet_id}") # Write header with workbook/sheet identifier ws.write_cell("A1", f"WB{workbook_id}_S{sheet_id}", dtype=DType.Str) # Write large data matrix data_matrix = np.random.randn(500, 50) ws.write_matrix((2, 0), data_matrix, dtype=DType.Float) # Write metadata ws.write_cell((0, 2), workbook_id, dtype=DType.Int) ws.write_cell((0, 3), sheet_id, dtype=DType.Int) ws.write_cell((0, 4), datetime.datetime.now(), dtype=DType.DateTime) sheets.append(ws) workbooks_to_write[f"output/batch_{workbook_id:03d}.xlsx"] = sheets # Write all 100 workbooks in parallel (6.3x faster than sequential) write_many(workbooks_to_write) ``` -------------------------------- ### Save Workbook in fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Saves the entire workbook, including all its worksheets and data, to a specified file path. This operation writes the workbook content to disk. ```python def save(path: str) -> None: """Save the workbook to the specified file path.""" pass ``` -------------------------------- ### Parallel Reading from Multiple Files with fastxlsx Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Read identical structures from multiple workbooks in parallel using Rust-native parallelism for linear performance scaling. This function accepts a dictionary where keys are file paths and values define the structure to read. It returns a nested dictionary containing the extracted data. ```python from fastxlsx import read_many, RangeInfo, DShape, DType # Read identical structure from 100 workbooks in parallel results = read_many({ f"reports/sales_{year}_{month:02d}.xlsx": { "Summary": { "monthly_total": RangeInfo((5, 10), DShape.Scalar(), dtype=DType.Float), "daily_sales": RangeInfo((10, 0), DShape.Column(30), dtype=DType.Float), "top_products": RangeInfo((50, 0), DShape.Column(10), dtype=DType.Str) } } for year in [2023, 2024] for month in range(1, 13) }) # Returns: { # "reports/sales_2023_01.xlsx": { # "Summary": { # "monthly_total": 458972.50, # "daily_sales": np.array([15234.0, 18903.0, ...]), # "top_products": ["Widget A", "Gadget B", ...] # } # }, # ... # } # Aggregation example total_revenue = sum( results[file]["Summary"]["monthly_total"] for file in results.keys() ) print(f"Total revenue: ${total_revenue:,.2f}") ``` -------------------------------- ### Read Multiple Worksheets in Python Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Demonstrates how to read data from multiple worksheets within a single workbook using FastXLSX. Allows specifying ranges by sheet name or index, and can handle complex data structures including nested dictionaries for metadata. ```python from fastxlsx import ReadOnlyWorkbook, RangeInfo, DShape, DType wb = ReadOnlyWorkbook("annual_data.xlsx") # Read from multiple worksheets using sheet names and indices results = wb.read_worksheets({ "Sheet1": [ RangeInfo((0, 0), DShape.Matrix(100, 10), dtype=DType.Float), RangeInfo((105, 0), DShape.Column(5), dtype=DType.Str) ], 0: [ # Same as "Sheet1" if it's the first sheet RangeInfo((2, 2), DShape.Scalar(), dtype=DType.Int) ], "Metadata": { "created_date": RangeInfo((0, 1), DShape.Scalar(), dtype=DType.Date), "author": RangeInfo((1, 1), DShape.Scalar(), dtype=DType.Str) } }) # Returns: { # "Sheet1": [np.ndarray(...), ["Header1", "Header2", ...]], # 0: [42], # "Metadata": { ``` -------------------------------- ### fastxlsx.WriteOnlyWorkbook Class Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Write-only workbook class for creating and writing data to new XLSX files. (Details for methods and attributes are not provided in the input text). ```APIDOC ## fastxlsx.WriteOnlyWorkbook ### Description Write-only workbook class. ### Note Detailed methods and attributes for this class were not available in the provided documentation snippet. ``` -------------------------------- ### Cell Address Conversion Utilities Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt This section provides utility functions for converting between 0-based row/column indices and Excel-style cell addresses (e.g., 'A1', 'AA6'). It shows how to use these functions for dynamic cell writing within a worksheet. ```python from fastxlsx import idx_to_addr, addr_to_idx, WriteOnlyWorkbook, DType # Convert indices to Excel addresses cell_addr1 = idx_to_addr(0, 0) # "A1" cell_addr2 = idx_to_addr(5, 26) # "AA6" cell_addr3 = idx_to_addr(100, 702) # "AAA101" # Convert Excel addresses to indices row, col = addr_to_idx("A1") # (0, 0) row, col = addr_to_idx("Z10") # (9, 25) row, col = addr_to_idx("BA100") # (99, 52) # Use in dynamic cell writing wb = WriteOnlyWorkbook() ws = wb.create_sheet("Dynamic") for i in range(10): for j in range(5): addr = idx_to_addr(i, j) ws.write_cell(addr, i * j, dtype=DType.Int) wb.save("dynamic_cells.xlsx") ``` -------------------------------- ### Create Worksheet in fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Creates a new worksheet within a workbook using the specified title. This method is part of the primary workbook object and returns a WriteOnlyWorksheet object. ```python def create_sheet(title: str) -> WriteOnlyWorksheet: """Create a new worksheet with the specified name.""" pass ``` -------------------------------- ### Parallel Batch Writing of Excel Files in Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/advanced_usage.md Demonstrates using FastXLSX's `write_many` function for efficient, parallelized writing of multiple Excel files. It generates 10 workbooks, each containing 6 sheets with headers and random float matrices, highlighting optimal performance for identical schemas. ```python import numpy as np from fastxlsx import DType, write_many, WriteOnlyWorksheet workbooks = {} for fid in range(10): # 10 output files sheets = [] for sid in range(6): # 6 sheets per file ws = WriteOnlyWorksheet(f"Sheet{sid}") # Header with workbook/sheet ID ws.write_cell("A1", 10*fid + sid, dtype=DType.Int) # 3x3 float matrix ws.write_matrix((1,1), np.random.rand(100,100), dtype=DType.Float) sheets.append(ws) workbooks[f"batch_{fid:02d}.xlsx"] = sheets write_many(workbooks) # Parallelized write ``` -------------------------------- ### Writing Rows, Columns, and Matrices with fastxlsx Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Efficiently write bulk data to Excel worksheets using NumPy arrays for numerical types. Supports writing entire rows, columns, or matrices. NumPy arrays are required for numerical types to ensure optimal performance and correct data handling. Mixed-type columns can be written using Python lists. ```python from fastxlsx import WriteOnlyWorkbook, DType import numpy as np wb = WriteOnlyWorkbook() ws = wb.create_sheet("Data") # Write a row of strings ws.write_row((0, 0), ["ID", "Name", "Score", "Grade"], dtype=DType.Str) # Write numerical row - MUST use NumPy array ws.write_row((1, 2), np.array([95.5, 87.3, 92.1]), dtype=DType.Float) # Write integer column - MUST use NumPy array ws.write_column((1, 0), np.array([1001, 1002, 1003], dtype=np.int64), dtype=DType.Int) # Write boolean column - MUST use NumPy array ws.write_column((1, 3), np.array([True, False, True]), dtype=DType.Bool) # Write matrix of random data random_matrix = np.random.randn(100, 50) ws.write_matrix((10, 0), random_matrix, dtype=DType.Float) # Write mixed-type column (allows Python list) ws.write_column((1, 4), [100, "passed", 3.14, datetime.date(2025, 12, 2)], dtype=DType.Any) # Write date column dates = [datetime.date(2025, 1, i) for i in range(1, 11)] ws.write_column((20, 0), dates, dtype=DType.Date) wb.save("bulk_data.xlsx") ``` -------------------------------- ### Parallel Writing to Multiple Files with fastxlsx Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Generate multiple workbooks simultaneously using Rust parallelism for maximum throughput. This feature allows for efficient creation of numerous Excel files concurrently. The `write_many` function is designed for this purpose, though its specific usage is not detailed in the provided snippet. ```python from fastxlsx import WriteOnlyWorksheet, write_many, DType import numpy as np workbooks_to_write = {} # Example usage would involve populating workbooks_to_write # and then calling write_many(workbooks_to_write) ``` -------------------------------- ### Read Worksheets from ReadOnlyWorkbook Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Demonstrates how to read data from multiple worksheets in a read-only workbook using specified ranges. It takes a dictionary mapping worksheet identifiers to a list or dictionary of RangeInfo objects and returns the read data. ```python from fastxlsx import WorkbookReanonly, RangeInfo, DShape, DType import numpy as np wb = WorkbookReanonly("example.xlsx") worksheets_to_read = { "Sheet1": [ RangeInfo((0, 0), DShape.Matrix(2, 2), dtype=DType.Int), RangeInfo((2, 0), DShape.Column(3), dtype=DType.Str), ], 1: [RangeInfo((0, 0), DShape.Row(5), dtype=DType.Float)], } res = wb.read_worksheets(worksheets_to_read) # Expected output structure (actual values depend on the file content): # { # "Sheet1": [np.array([[1, 2], [3, 4]]), ["A", "B", "C"]], # 1: [np.array([1.1, 2.2, 3.3, 4.4, 5.5])], # } ``` -------------------------------- ### Batch Read Multiple Ranges in Python Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Illustrates how to read multiple ranges from a single worksheet simultaneously using FastXLSX. Supports reading named ranges into a dictionary or indexed ranges into a list. This is efficient for extracting related data sets in one operation. ```python from fastxlsx import ReadOnlyWorkbook, RangeInfo, DShape, DType wb = ReadOnlyWorkbook("financial_report.xlsx") ws = wb.get_by_name("Summary") # Read multiple named ranges as dictionary data = ws.read_values({ "revenue": RangeInfo((5, 2), DShape.Column(12), dtype=DType.Float), "expenses": RangeInfo((5, 3), DShape.Column(12), dtype=DType.Float), "profit_margin": RangeInfo((20, 5), DShape.Scalar(), dtype=DType.Float), "categories": RangeInfo((5, 0), DShape.Column(12), dtype=DType.Str) }) # Returns: { # "revenue": np.array([105000.0, 98000.0, ...]), # "expenses": np.array([85000.0, 72000.0, ...]), # "profit_margin": 0.287, # "categories": ["Jan", "Feb", "Mar", ...] # } # Read multiple ranges as list ranges_list = ws.read_values([ RangeInfo((0, 0), DShape.Matrix(10, 5), dtype=DType.Int), RangeInfo((15, 0), DShape.Row(8), dtype=DType.Bool) ]) # Returns: [np.array([[1, 2, 3, 4, 5], ...]), np.array([True, False, ...])] ``` -------------------------------- ### Type Safety and Validation for Data Reading Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt This code demonstrates how to enforce data types and handle validation when reading data from Excel files using `ReadOnlyWorkbook`. It illustrates both strict mode (raising errors on mismatch) and lenient mode (substituting default values). ```python from fastxlsx import ReadOnlyWorkbook, RangeInfo, DShape, DType import numpy as np import datetime wb = ReadOnlyWorkbook("user_data.xlsx") ws = wb.get(0) # Strict mode (default) - raises ValueError on type mismatch try: ages = ws.read_value( RangeInfo((1, 2), DShape.Column(100), dtype=DType.Int, strict=True) ) except ValueError as e: print(f"Data validation failed: {e}") # Handle error: log, skip, or fix invalid data # Lenient mode - substitutes default values on type mismatch ages_lenient = ws.read_value( RangeInfo((1, 2), DShape.Column(100), dtype=DType.Int, strict=False) ) # Invalid cells become 0 (Int default) # Default values by type: # DType.Bool -> False # DType.Int -> 0 # DType.Float -> nan # DType.Date/DateTime -> 1970-01-01 # DType.Str -> "" # DType.Any -> None # Type-specific reading with validation email_col = ws.read_value( RangeInfo((1, 4), DShape.Column(100), dtype=DType.Str, strict=True) ) date_col = ws.read_value( RangeInfo((1, 5), DShape.Column(100), dtype=DType.Date, strict=False) ) # Invalid dates become datetime.date(1970, 1, 1) # Verify numerical data quality scores = ws.read_value( RangeInfo((1, 6), DShape.Column(100), dtype=DType.Float, strict=False) ) valid_scores = scores[~np.isnan(scores)] print(f"Valid scores: {len(valid_scores)}/{len(scores)}") ``` -------------------------------- ### Retrieve Worksheet by Index or Name in fastxlsx Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Retrieves an existing worksheet from the workbook either by its 0-based index or its title string. Returns a WriteOnlyWorksheet object. ```python def get(idx_or_title: Union[int, str]) -> WriteOnlyWorksheet: """Get a worksheet by its index or name.""" pass ``` -------------------------------- ### Parallel Batch Reading of Excel Files in Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/advanced_usage.md Illustrates parallelized reading of multiple Excel files using FastXLSX's `read_many` function. It defines a structure to read specific data ranges (header integer and float matrix) from multiple sheets across various workbooks, demonstrating efficient data aggregation. ```python from fastxlsx import read_many, RangeInfo, DShape, DType results = read_many({ f"batch_{fid:02d}.xlsx": { f"Sheet{sid}": [ RangeInfo((0,0), DShape.Scalar(), dtype=DType.Int), # Read header RangeInfo((1,1), DShape.Matrix(100,100), dtype=DType.Float) # Extract 3x3 matrix ] for sid in range(6) } for fid in range(10) }) ``` -------------------------------- ### fastxlsx.DShape Classes Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Classes to describe the shape of data within a range. These are used in conjunction with RangeInfo to define the dimensions of data to be read or written. ```APIDOC ## fastxlsx.DShape ### Description Classes to describe the shape of data. ### Aliases - **Column**: alias of `DShape_Column` - **Matrix**: alias of `DShape_Matrix` - **Row**: alias of `DShape_Row` - **Scalar**: alias of `DShape_Scalar` ``` -------------------------------- ### Read Multiple Values using RangeInfo List/Dict Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Demonstrates reading multiple values from a worksheet based on a list or dictionary of RangeInfo objects. The function returns a list or dictionary containing the values read from each specified range. ```python from fastxlsx import RangeInfo, DShape, DType # Assuming 'worksheet' is an instance of ReadOnlyWorksheet # Example with a list of RangeInfo objects: # range_infos_list = [ # RangeInfo((0, 0), DShape.Matrix(2, 2), dtype=DType.Int), # RangeInfo((2, 0), DShape.Column(3), dtype=DType.Str) # ] # values_list = worksheet.read_values(range_infos_list) # Example with a dictionary of RangeInfo objects: # range_infos_dict = { # "data1": RangeInfo((0, 0), DShape.Matrix(2, 2), dtype=DType.Int), # "data2": RangeInfo((2, 0), DShape.Column(3), dtype=DType.Str) # } # values_dict = worksheet.read_values(range_infos_dict) ``` -------------------------------- ### Read Ranges with RangeInfo in Python Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Shows how to read structured data ranges from a worksheet using `RangeInfo` with FastXLSX. Supports reading columns, rows, matrices, and scalar values with explicit data type declarations. Returns NumPy arrays for numerical data and Python lists for mixed types. ```python from fastxlsx import ReadOnlyWorkbook, RangeInfo, DShape, DType import numpy as np wb = ReadOnlyWorkbook("sales.xlsx") ws = wb.get("Q4 Report") # Read a single column of strings names = ws.read_value( RangeInfo((4, 0), DShape.Column(10), dtype=DType.Str) ) # Returns: ["Alice", "Bob", "Charlie", ...] # Read a row of floats as NumPy array prices = ws.read_value( RangeInfo((0, 5), DShape.Row(20), dtype=DType.Float) ) # Returns: np.array([19.99, 24.50, 15.75, ...]) # Read a matrix of integers sales_data = ws.read_value( RangeInfo((2, 2), DShape.Matrix(50, 12), dtype=DType.Int) ) # Returns: np.ndarray with shape (50, 12) # Read a scalar value total = ws.read_value( RangeInfo((60, 15), DShape.Scalar(), dtype=DType.Float) ) # Returns: 125847.32 # Read mixed-type column (slower but flexible) mixed_col = ws.read_value( RangeInfo((0, 3), DShape.Column(5), dtype=DType.Any) ) # Returns: [42, "text", 3.14, True, datetime.date(2025, 12, 2)] ``` -------------------------------- ### Convert Index to Cell Address - Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Converts a 0-based (row, column) tuple index into a standard Excel cell address string (e.g., 'A1', 'B2'). This function complements `addr_to_idx` by providing the reverse functionality. ```python from fastxlsx import idx_to_addr row_index = 4 col_index = 2 cell_address = idx_to_addr(row_index, col_index) print(f"The address for index ({row_index}, {col_index}) is: {cell_address}") # Expected output: The address for index (4, 2) is: C5 ``` -------------------------------- ### Write Multiple Workbooks - Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Writes data to multiple Excel workbooks concurrently. It accepts a dictionary where keys are workbook file paths and values are lists of WriteOnlyWorksheet objects. Each WriteOnlyWorksheet object contains the data and formatting for a single sheet within a workbook. This function is useful for generating multiple reports or data files efficiently. ```python from fastxlsx import DType, WriteOnlyWorksheet, write_many import numpy as np # Example usage: workbooks_to_write = {} for i_workbook in range(10): ws_list = [] for i_sheet in range(6): ws = WriteOnlyWorksheet(f"Sheet{i_sheet}") ws.write_cell("A1", 10 * i_workbook + i_sheet, dtype=DType.Int) ws.write_matrix((1, 1), np.random.random((3, 3)), dtype=DType.Float) ws_list.append(ws) workbooks_to_write[f"workboopk_{i_workbook}.xlsx"] = ws_list write_many(workbooks_to_write) # This will create 10 Excel files, each with 6 worksheets. ``` -------------------------------- ### Lenient Mode for Type Conversion in Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/advanced_usage.md Shows how to use FastXLSX in lenient mode (strict=False) for type enforcement. Invalid values are replaced with type-specific defaults, as demonstrated with a date dtype where incorrect entries default to '1970-01-01'. ```python ws.read_value( RangeInfo((0,0), DShape.Row(3), dtype=DType.Date, strict=False) ) # Returns: [date(1970,1,1), date(2025,2,3), date(1970,1,1)] ``` -------------------------------- ### Read Multiple Workbooks with Ranges - Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Reads data from multiple Excel workbooks based on specified ranges within worksheets. It takes a dictionary where keys are workbook paths and values are dictionaries mapping worksheet identifiers to lists of RangeInfo objects. The function returns a nested dictionary with the same structure, but with RangeInfo objects replaced by the actual data read from the cells. ```python from fastxlsx import RangeInfo, DShape, DType, read_many # Assuming WorkbookReanonly and necessary imports are available # Example usage: workbooks_to_read = { "workbook1.xlsx": { "Sheet1": [ RangeInfo((0, 0), DShape.Matrix(2, 2), dtype=DType.Int), RangeInfo((2, 0), DShape.Column(3), dtype=DType.Str), ], 1: [RangeInfo((0, 0), DShape.Row(5), dtype=DType.Float)], }, "workbook2.xlsx": { 0: [RangeInfo((0, 0), DShape.Scalar(), dtype=DType.Str)], }, } res = read_many(workbooks_to_read) # res will contain the read data ``` -------------------------------- ### Read Single Value using RangeInfo Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Shows how to read a single value from a worksheet using a RangeInfo object. The RangeInfo specifies the position, shape, and data type of the value to be read. The return type can be a scalar, 1D array, or 2D array. ```python from fastxlsx import RangeInfo, DShape, DType # Assuming 'worksheet' is an instance of ReadOnlyWorksheet # Example: reading a 2x2 matrix of integers starting from (0,0) # range_info = RangeInfo((0, 0), DShape.Matrix(2, 2), dtype=DType.Int) # value = worksheet.read_value(range_info) ``` -------------------------------- ### Convert Cell Address to Index - Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Converts a human-readable cell address string (e.g., 'A1', 'B2') into a 0-based (row, column) tuple index. This is useful for programmatic manipulation of spreadsheet data where integer coordinates are preferred. ```python from fastxlsx import addr_to_idx cell_address = "C5" row_col_index = addr_to_idx(cell_address) print(f"The index for {cell_address} is: {row_col_index}") # Expected output: The index for C5 is: (4, 2) ``` -------------------------------- ### Reading Excel Data with Explicit Typing in Python Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/advanced_usage.md Demonstrates reading cell values from an Excel worksheet using FastXLSX. It contrasts auto-detection (slower, returns a list) with type-enforced reading (faster, returns a NumPy ndarray) by specifying the DType in RangeInfo. ```python from fastxlsx import DType, RangeInfo # Auto-detected (slower, returns list) data_list = ws.read_value(RangeInfo((5,2), DShape.Row(3))) # Type-enforced (faster, returns ndarray) data_array = ws.read_value( RangeInfo((5,2), DShape.Row(3), dtype=DType.Float) ) ``` -------------------------------- ### fastxlsx.DType Enumeration Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Enumeration for data types supported by fastxlsx. These types can be used to specify expected data types when reading or writing cells. ```APIDOC ## fastxlsx.DType ### Description Enumeration for data types. ### Members - **Any** - **Bool** - **Date** - **DateTime** - **Float** - **Int** - **Str** ``` -------------------------------- ### Writing Individual Cells with fastxlsx Source: https://context7.com/shuangluoxss/fastxlsx/llms.txt Write single values to specific cells in an Excel worksheet using `WriteOnlyWorkbook` and `WriteOnlyWorksheet`. Explicit type declarations using `DType` improve performance. This method supports various data types including strings, integers, floats, booleans, dates, and datetimes. ```python from fastxlsx import WriteOnlyWorkbook, WriteOnlyWorksheet, DType import datetime wb = WriteOnlyWorkbook() ws = wb.create_sheet("Report") # Write string (auto-detect type) ws.write_cell((0, 0), "Annual Sales Report") # Write with explicit types (faster) ws.write_cell((1, 0), 42, dtype=DType.Int) ws.write_cell("B2", 3.14159, dtype=DType.Float) ws.write_cell((2, 0), True, dtype=DType.Bool) ws.write_cell("D2", datetime.date.today(), dtype=DType.Date) ws.write_cell((3, 0), datetime.datetime.now(), dtype=DType.DateTime) # Mixed types without explicit dtype (slower) ws.write_cell((4, 0), "Total") ws.write_cell((4, 1), 15847.25) wb.save("output.xlsx") ``` -------------------------------- ### Write Cell Value in fastxlsx.WriteOnlyWorksheet Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Writes a single value to a specific cell within a worksheet. Supports cell addressing by coordinate tuple (row, col) or string notation (e.g., 'A1'). Allows optional data type enforcement. ```python def write_cell(cell_addr: Union[Tuple[int, int], str], value: Any, *, dtype=DType.Any) -> None: """Write a value to a specific cell in the worksheet.""" pass ``` -------------------------------- ### fastxlsx.ReadOnlyWorksheet Class Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Read-only worksheet class for interacting with a single sheet in an XLSX file. Allows reading specific cells or ranges of cells. ```APIDOC ## fastxlsx.ReadOnlyWorksheet ### Description Read-only worksheet class. ### Methods #### cell_value(cell_addr, *, dtype=Ellipsis, strict=True) Read a value from a specific cell in the worksheet. - **Parameters**: - **cell_addr** (Union[Tuple[int, int], str]) - The cell address, either as (row, col) or a string (e.g., “A1”). - **dtype** ([*DType*](#fastxlsx.DType), optional) - The expected data type. Defaults to DType.Any. - **strict** (bool, optional) - Whether to enforce strict type checking. Defaults to True. - **Returns**: The value read from the cell. - **Return type**: Any #### read_value(range_info) Read a single value from the worksheet based on the specified range. - **Parameters**: - **range_info** ([*RangeInfo*](#fastxlsx.RangeInfo)) - The range information. - **Returns**: The value read from the range. - **Return type**: Any #### read_values(range_infos) Read multiple values from the worksheet based on a list of ranges. - **Parameters**: - **range_infos** (List[RangeInfo] | Dict[str, RangeInfo]) - A list or dict of RangeInfo objects. - **Returns**: A list or dict of values read from the specified ranges. - **Return type**: List[Any] | Dict[str, Any] ### Attributes - **n_cols** (int) - The number of columns in the worksheet. - **n_rows** (int) - The number of rows in the worksheet. - **title** (str) - The title (name) of the worksheet. ``` -------------------------------- ### Read Cell Value from ReadOnlyWorksheet Source: https://github.com/shuangluoxss/fastxlsx/blob/main/docs/api.md Illustrates how to read a single cell's value from a read-only worksheet. It allows specifying the cell address, expected data type, and strict type checking behavior. Returns the cell's value. ```python from fastxlsx import ReadOnlyWorksheet, DType # Assuming 'worksheet' is an instance of ReadOnlyWorksheet # Example: reading value from cell B2 with integer type # cell_value = worksheet.cell_value((1, 1), dtype=DType.Int) # Example: reading value from cell A1 as any type (auto-detected) # cell_value_any = worksheet.cell_value("A1", dtype=DType.Any) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.