For command line data processing, CSV is almost always the right choice because it is plain text, universally supported by standard Unix tools, and easy to script. XLSX is a binary, compressed format that requires special libraries and is slower to work with. However, there are specific cases where XLSX is necessary, such as when you need to preserve formulas, multiple sheets, or formatting. This guide will walk you through the decision process and show you how to handle both formats from the command line.

What You'll Need

  • A Unix-like environment (Linux, macOS, or Windows Subsystem for Linux) with standard tools like grep, awk, sed, and sort.
  • Python 3 with the pandas library installed (for reading and writing XLSX files). Install with pip install pandas openpyxl.
  • Optionally, csvkit for advanced CSV operations (pip install csvkit).
  • Basic familiarity with the command line and shell scripting.

Step-by-Step

  1. Identify your primary use case. Ask yourself: Do you need to process data with standard tools like grep, awk, or sort? Do you need to combine multiple files easily? Do you need to preserve formulas, multiple sheets, or cell formatting? If the answer to the first two is yes and the last is no, choose CSV. If you need multiple sheets or formulas, you may need XLSX, but you will have to convert to CSV for most command line operations.
  2. Check the source of your data. If you are exporting data from a database or an API, CSV is often the native export format. If you are receiving data from a colleague or a client, it may come as XLSX. In that case, you will need to convert it to CSV before processing.
  3. Convert XLSX to CSV. When you have an XLSX file, use Python with pandas to convert it to CSV. Create a script like this:
    import pandas as pd
    import sys
    
    input_file = sys.argv[1]
    output_file = sys.argv[2]
    

    Read the first sheet by default; specify sheet_name='Sheet2' for others

    df = pd.read_excel(input_file, sheet_name=0) df.to_csv(output_file, index=False)
    Save as convert_xlsx_to_csv.py and run python convert_xlsx_to_csv.py data.xlsx data.csv. This will extract the first sheet. If you need a specific sheet, change sheet_name=0 to the sheet name or index.
  4. Handle multiple sheets. If your XLSX has multiple sheets, you can either convert each sheet separately or combine them. To list sheet names, use python -c "import pandas as pd; print(pd.ExcelFile('data.xlsx').sheet_names)". Then convert each sheet by modifying the script to loop over all sheets, or use the sheet_name=None option to get a dictionary of DataFrames.
  5. Process the CSV with standard tools. Once you have a CSV, you can use standard commands. For example, to filter rows where the second column equals "active", use awk -F',' '$2 == "active"' data.csv. To sort by the first column, use sort -t',' -k1,1 data.csv. To count unique values in the third column, use cut -d',' -f3 data.csv | sort | uniq -c.
  6. Handle CSV quirks. CSV files can have quoted fields with commas, newlines, or escaped quotes. For robust parsing, use a proper CSV library. In Python, use csv module or pandas. For command line, use csvkit's csvgrep and csvgrep commands. For example, csvgrep -c 2 -m active data.csv filters rows where column 2 matches "active".
  7. Convert CSV back to XLSX if needed. If your final output must be XLSX (for example, to send to a non-technical colleague), convert back using pandas. A simple script:
    import pandas as pd
    import sys
    
    df = pd.read_csv(sys.argv[1])
    df.to_excel(sys.argv[2], index=False)
    Run python convert_csv_to_xlsx.py data.csv data.xlsx.
  8. Consider using a data processing tool. For more complex transformations, consider using jq for JSON, but for tabular data, csvkit provides csvgrep, csvgrep, csvjoin, and csvstat. These are more reliable than raw awk for messy CSV data.
  9. Automate the workflow. Write a shell script that converts XLSX to CSV, processes it, and converts back if needed. For example:
    #!/bin/bash
    python convert_xlsx_to_csv.py "$1" temp.csv
    

    Process temp.csv with standard tools

    sort -t',' -k1,1 temp.csv -o sorted.csv python convert_csv_to_xlsx.py sorted.csv "${1%.xlsx}_processed.xlsx" rm temp.csv sorted.csv
  10. Test with a small sample. Before running on a large file, test your pipeline on a small sample to ensure the data is parsed correctly. Use head -n 100 data.csv to inspect the first few rows.

Common Mistakes

  • Using XLSX directly with Unix tools. Tools like grep or awk cannot read XLSX because it is a binary format. You will get binary garbage or errors. Always convert to CSV first.
  • Ignoring CSV quoting. If a field contains a comma, it is quoted in CSV. A naive cut -d',' will split it incorrectly. Always use a proper CSV parser.
  • Assuming all XLSX files have the same structure. Sheet names, column order, and data types vary. Always inspect the file before processing.
  • Forgetting about encoding. CSV files may be in UTF-8, but sometimes they are in Latin-1 or other encodings. Use file data.csv to check, and convert with iconv if needed.
  • Overwriting the original file. When converting, use a different output filename to avoid accidental data loss.

Tips

  • Use csvkit for complex CSV operations. It handles quoting, encoding, and provides SQL-like queries. For example, csvgrep -c 1 -r '^[0-9]+$' data.csv filters rows where column 1 is all digits.
  • Keep a backup of the original XLSX. If you convert to CSV, you lose formulas, formatting, and multiple sheets. Keep the original for reference.
  • Use head and tail to inspect large files. Before running a heavy operation, check the first few rows to verify the format.
  • Consider using pandas for complex transformations. If you need to join, pivot, or aggregate data, pandas is more powerful than shell tools.
  • Use in2csv from csvkit. It can convert XLSX to CSV with one command: in2csv data.xlsx > data.csv. It also supports other formats like JSON.

Troubleshooting

If your conversion or processing fails, follow these steps:

  1. Check the file path and permissions. Ensure the file exists and is readable. Use ls -l to check.
  2. Verify the XLSX is not corrupted. Try opening it in a spreadsheet application. If it won't open, the file may be damaged.
  3. Check for password protection. If the XLSX is password-protected, pandas will fail. You will need to remove the password first.
  4. Inspect the CSV output. After conversion, run head -n 5 data.csv to see if the data looks correct. Look for missing columns or garbled text.
  5. Handle encoding issues. If you see mojibake, use iconv -f ISO-8859-1 -t UTF-8 data.csv > data_utf8.csv (adjust the source encoding).
  6. If pandas fails with "No module named 'openpyxl'", install it with pip install openpyxl.

Frequently Asked Questions

Can I use grep directly on an XLSX file?

No, grep treats the file as binary and will output binary data or errors. You must convert to CSV first.

What if I need to process multiple sheets from an XLSX?

Convert each sheet to a separate CSV using pandas with sheet_name parameter, or combine them into one CSV with a column indicating the sheet name.

Is CSV faster than XLSX for processing?

Yes, CSV is plain text and can be processed with fast, native tools. XLSX requires parsing compressed XML, which is slower.

Can I preserve formulas when converting to CSV?

No, CSV stores only the computed values, not the formulas. If you need formulas, keep the XLSX and process it with a library that supports formulas, like openpyxl with data_only=False.

What about CSV files with semicolons as delimiters?

Some locales use semicolons. Specify the delimiter in pandas with sep=';' or in csvkit with --delimiter ';'.

Should I use Python or shell tools for CSV processing?

For simple operations, shell tools are faster and more concise. For complex transformations, Python with pandas is more maintainable and robust.