How to Save Spreadsheets as CSV in Python
Problem
Save an Excel workbook (.xlsx) as a CSV file using Aspose.Cells FOSS in Python. Load the workbook with Workbook(), then call save_as_csv() to write the active worksheet to a comma-separated values file. Optionally pass a CSVSaveOptions object to control the delimiter, encoding, and quote behaviour.
Prerequisites
To save spreadsheets as CSV using Aspose.Cells FOSS in Python, ensure your environment meets the following requirements.
- Python 3.7 or later installed
- Install Aspose.Cells FOSS via
pip install aspose-cells-foss>=26.3.1 - Import the library using
from aspose.cells_foss import Workbook - Basic familiarity with Python file handling
Saving Steps
Step 1: Install the Library
Install Aspose.Cells FOSS from PyPI. No licence file is required for FOSS use.
pip install aspose-cells-fossStep 2: Load the Workbook
Instantiate Workbook with the path to an existing .xlsx file. The constructor accepts an optional password parameter for protected workbooks.
from aspose.cells_foss import Workbook
workbook = Workbook("input.xlsx")To work with a brand-new workbook instead, omit the file path:
from aspose.cells_foss import Workbook
workbook = Workbook()
worksheet = workbook.worksheets[0]
# Populate some cells
worksheet.cells["A1"].value = "Product"
worksheet.cells["B1"].value = "Price"
worksheet.cells["A2"].value = "Widget"
worksheet.cells["B2"].value = 9.99
worksheet.cells["A3"].value = "Gadget"
worksheet.cells["B3"].value = 24.95Step 3: Save the Active Sheet as CSV
Call Workbook.save_as_csv() with the desired output path. The method writes the first (active) worksheet by default.
workbook.save_as_csv("output.csv")Alternatively, use the generic Workbook.save() method — Aspose.Cells FOSS infers the CSV format from the .csv extension:
workbook.save("output.csv")Both calls produce identical output when no custom options are needed.
Step 4: Save with CSV Options
Workbook.save_as_csv() accepts an optional CSVSaveOptions instance as its second argument. Instantiate CSVSaveOptions from aspose.cells_foss.csv_handler and pass it directly to control export behaviour, such as choosing a non-default delimiter or encoding.
from aspose.cells_foss import Workbook
from aspose.cells_foss.csv_handler import CSVSaveOptions
workbook = Workbook("input.xlsx")
# Create options instance — configure attributes per your environment's needs
options = CSVSaveOptions()
workbook.save_as_csv("output_custom.csv", options)When no CSVSaveOptions is passed, save_as_csv() uses the library’s built-in defaults (comma delimiter, UTF-8 encoding). Pass the options object whenever you need to override those defaults programmatically.
Step 5: Export a Specific Worksheet
When a workbook contains multiple sheets, the active sheet is exported. Use Workbook.set_active_worksheet() to choose which sheet to export before saving.
from aspose.cells_foss import Workbook
workbook = Workbook("multi_sheet.xlsx")
# Export the second worksheet (index 1)
workbook.set_active_worksheet(1)
workbook.save_as_csv("sheet2_output.csv")To export every sheet to its own CSV file, iterate over workbook.worksheets:
from aspose.cells_foss import Workbook
workbook = Workbook("multi_sheet.xlsx")
for index in range(len(workbook.worksheets)):
ws = workbook.get_worksheet_by_index(index)
workbook.set_active_worksheet(index)
workbook.save_as_csv(f"sheet_{ws.name}.csv")Complete Example
The following self-contained example creates a workbook, fills it with sample data, and saves it as both a standard CSV and a semicolon-delimited CSV.
from aspose.cells_foss import Workbook
from aspose.cells_foss.csv_handler import CSVSaveOptions
# Create workbook and populate data
workbook = Workbook()
worksheet = workbook.worksheets[0]
headers = ["Name", "Department", "Salary"]
rows = [
["Alice", "Engineering", 95000],
["Bob", "Marketing", 72000],
["Carol", "Finance", 81000],
]
for col, header in enumerate(headers):
col_letter = chr(ord("A") + col)
worksheet.cells[f"{col_letter}1"].value = header
for row_idx, row in enumerate(rows, start=2):
for col_idx, val in enumerate(row):
col_letter = chr(ord("A") + col_idx)
worksheet.cells[f"{col_letter}{row_idx}"].value = val
# Save as standard CSV (default options)
workbook.save_as_csv("employees.csv")
# Save with explicit CSVSaveOptions instance
options = CSVSaveOptions()
workbook.save_as_csv("employees_custom.csv", options)
print("CSV files written successfully.")Common Issues
Empty Output File
If the output CSV is empty or contains only blank lines, verify that cell values were assigned before calling save_as_csv(). The method exports the active worksheet — confirm the correct sheet is active using workbook.get_active_worksheet().
Encoding Problems (Garbled Characters)
When opening a CSV in Excel and seeing corrupted characters, verify the encoding used during export. Aspose.Cells FOSS defaults to UTF-8; Excel on Windows may expect a byte-order mark (BOM) to recognise the encoding correctly. Configure encoding via CSVSaveOptions and pass it to save_as_csv().
Multi-Sheet Workbooks Export Only One Sheet
CSV is a single-table format; only one worksheet can be saved per file. Export each sheet individually using set_active_worksheet(index) as shown in Step 5.
Cells Containing the Delimiter
If a cell value contains the delimiter character (e.g., a comma in comma-delimited output), Aspose.Cells FOSS automatically quotes the value during export. Use CSVSaveOptions to customise quoting behaviour if needed.
FAQ
Q: Does workbook.save("output.csv") produce the same result as save_as_csv()?
Yes. Workbook.save() inspects the file extension and delegates to save_as_csv() when the extension is .csv. Call save_as_csv() directly and pass a CSVSaveOptions instance when you need to customise the export beyond the built-in defaults.
Q: Can I export to a CSV string instead of a file?
Yes. Use CSVHandler.save_csv_to_string(workbook, options) from aspose.cells_foss.csv_handler. This returns the CSV content as a Python string, which you can write to a stream, upload, or further process without touching the filesystem.
from aspose.cells_foss import Workbook
from aspose.cells_foss.csv_handler import CSVHandler, CSVSaveOptions
workbook = Workbook("input.xlsx")
csv_string = CSVHandler().save_csv_to_string(workbook, CSVSaveOptions())
print(csv_string)Q: How do I load a CSV back into a workbook after saving?
Use Workbook.load_csv("file.csv") on an existing Workbook instance, or call the convenience function load_csv_workbook("file.csv") from aspose.cells_foss.csv_handler to get a ready-to-use workbook in one step.
Q: What Python versions are supported?
Aspose.Cells FOSS requires Python 3.7 or later. No additional native extensions are needed for CSV export; the library is pure Python.
Q: Can I save only part of a worksheet (a cell range) as CSV?
Aspose.Cells FOSS exports the full used range of the active worksheet. To restrict output to a specific range, copy the desired cells into a temporary workbook and export that workbook.
See Also
- How to Save Files with Aspose.Cells FOSS — general save overview covering XLSX and Markdown
- How to Convert CSV to JSON in Python — load CSV and export to JSON format
- How to Export Excel to Markdown in Python — Markdown table export using
save_as_markdown() - Aspose.Cells FOSS for Python: Developer Guide — comprehensive feature documentation
- API Reference —
Workbook,CSVHandler,CSVSaveOptions