save_spreadsheet

pyhelpers.store.save_spreadsheet(data, path_to_file, sheet_name='Sheet1', index=False, engine=None, delimiter=',', autofit_column_width=True, writer_kwargs=None, verbose=False, **kwargs)[source]

Save data to a spreadsheet file format (e.g. CSV, Microsoft Excel or OpenDocument).

The file format is determined by the extension of path_to_file, which can be ".txt", ".csv", ".xlsx" or ".xls". The saving engine may use xlsxwriter, openpyxl or odfpy.

Parameters:
  • data (pandas.DataFrame) – Data to be saved as a spreadsheet.

  • path_to_file (str | os.PathLike[str] | None) – File path where the spreadsheet will be saved.

  • sheet_name (str) – Name of the sheet where the data will be saved; defaults to "Sheet1".

  • index (bool) – Whether to include the dataframe index as a column; defaults to False.

  • engine (str | None) –

    Engine to use for saving:

  • delimiter (str) – Separator for ".csv", ".txt" or ".odt" file formats; defaults to ','.

  • autofit_column_width (bool) – Whether to autofit column width; defaults to True.

  • writer_kwargs (dict | None) – [Optional] Additional parameters for the class pandas.ExcelWriter().

  • verbose (bool | int) – Whether to print relevant information to the console; defaults to False.

  • kwargs – [Optional] Additional parameters for the method pandas.DataFrame.to_excel() or pandas.DataFrame.to_csv().

Examples:

>>> from pyhelpers.store import save_spreadsheet
>>> from pyhelpers.dirs import cd
>>> from pyhelpers._cache import example_dataframe
>>> # Get an example dataframe
>>> spreadsheet_dat = example_dataframe()
>>> spreadsheet_dat
            Longitude   Latitude
City
London      -0.127647  51.507322
Birmingham  -1.902691  52.479699
Manchester  -2.245115  53.479489
Leeds       -1.543794  53.797418
>>> spreadsheet_pathname = cd("tests\data", "dat.csv")
>>> save_spreadsheet(spreadsheet_dat, spreadsheet_pathname, index=True, verbose=True)
Saving "dat.csv" to "tests\data\" ... Done.
>>> spreadsheet_pathname = cd("tests\data", "dat.xlsx")
>>> save_spreadsheet(spreadsheet_dat, spreadsheet_pathname, index=True, verbose=True)
Saving "dat.xlsx" to "tests\data\" ... Done.
>>> spreadsheet_pathname = cd("tests\data", "dat.ods")
>>> save_spreadsheet(spreadsheet_dat, spreadsheet_pathname, index=True, verbose=True)
Saving "dat.ods" to "tests\data\" ... Done.