Using xlsxgrep as a Python Module
In addition to command-line usage, xlsxgrep can be imported directly into Python applications.
This guide demonstrates how to invoke search operations programmatically, retrieve structured output, and build interactive tools.
Structured results use spreadsheet display values for numeric cells in XLSX, XLSM, XLS, and ODS files. For example, a currency cell is returned as its displayed currency text rather than its raw stored number; CSV and TSV values are returned as stored.
Example 1: Standard usage with process_single_file (returns structured results)
Use process_single_file when you want to handle search results programmatically without printing directly to standard output:
import xlsxgrep
# Configure search options
opts = {
"PATTERN": "Software",
"python_regex": False,
"fixed_strings": False,
"ignore_case": True,
"word_regexp": False,
"count": False,
"recursive": False,
"with_filename": True,
"with_sheetname": True,
"files_with_match": False,
"files_without_match": False,
"separator": "\t",
"null": False,
"debug": False,
"row": True,
"column": False,
"jobs": 1,
}
# Run search on a single spreadsheet file
result = xlsxgrep.process_single_file("my_data.xlsx", opts)
# Access formatted output and counts directly
print("Matching lines:")
for line in result["stdout"]:
print(line.strip())
row_count, cell_count, string_count = result["counts"]
print(f"Summary: {row_count} rows, {cell_count} cells, {string_count} strings")
Example 2: Batch search across multiple files with SEARCH
Use SEARCH to run batch operations over a list of files or directories with multi-processing support:
import xlsxgrep
files = ["file1.xlsx", "file2.csv", "file3.ods"]
opts = {
"PATTERN": "[0-9]+",
"python_regex": True,
"fixed_strings": False,
"ignore_case": False,
"word_regexp": False,
"count": True,
"recursive": False,
"with_filename": True,
"with_sheetname": False,
"files_with_match": False,
"files_without_match": False,
"separator": "\t",
"null": False,
"debug": False,
"row": True,
"column": False,
"jobs": 4, # Use 4 parallel CPU processes
}
# Prints results directly to stdout/stderr
xlsxgrep.SEARCH(files, opts)
Interactive Script Example
Below is a complete script example that prompts the user for a search pattern, accepts optional inputs, and executes xlsxgrep programmatically:
#!/usr/bin/env python3
import sys
import xlsxgrep
def run_interactive_xlsxgrep():
print(f"=== xlsxgrep v{xlsxgrep.__version__} Interactive Runner ===")
# 1. Prompt user for pattern
pattern = input("Enter search pattern: ").strip()
if not pattern:
print("Error: Search pattern cannot be empty.")
sys.exit(1)
# 2. Prompt user for file or directory path
file_path = input("Enter file or folder path [default: .]: ").strip() or "."
# 3. Prompt user for search options
ignore_case_input = input("Ignore case? (y/N): ").strip().lower()
ignore_case = ignore_case_input.startswith("y")
use_regex_input = input("Use Python Regex? (y/N): ").strip().lower()
python_regex = use_regex_input.startswith("y")
# 4. Build configuration dictionary
opts = {
"PATTERN": pattern,
"python_regex": python_regex,
"fixed_strings": not python_regex,
"ignore_case": ignore_case,
"word_regexp": False,
"count": False,
"recursive": True,
"with_filename": True,
"with_sheetname": True,
"files_with_match": False,
"files_without_match": False,
"separator": "\t",
"null": False,
"debug": False,
"row": True,
"column": False,
"jobs": 0, # 0 auto-detects CPU cores
}
print("\nRunning search...\n" + "-" * 50)
# 5. Execute search using imported xlsxgrep
results = xlsxgrep.process_single_file(file_path, opts)
# 6. Display results
if results["stdout"]:
for line in results["stdout"]:
print(line, end="")
else:
print("No matches found.")
if results["stderr"]:
for err in results["stderr"]:
sys.stderr.write(err)
if __name__ == "__main__":
run_interactive_xlsxgrep()
Sample Interactive Output
=== xlsxgrep 0.0.38 Interactive Runner ===
Enter search pattern: Software
Enter file or folder path [default: .]: tests/Financials Sample Data 1.csv
Ignore case? (y/N): y
Use Python Regex? (y/N): n
Running search...
--------------------------------------------------
tests/Financials Sample Data 1.csv: Financials Sample Data 1.csv: Sales Software USD 2012 Actuals $90,924,002 ...