Print Excel Workbook Using Python

Printing an Excel workbook may mean – reading and displaying the contents of an Excel file on the console or printing the XLSX file into a file. The second option may involve sending the Excel file to a printer machine for physical printing.

This article discusses those two options. Note that both of these methods require you to have Excel Application installed – Microsoft Excel for Windows and Mac or Libre Office for Linux and Mac

Printing Excel Workbook into File using Python

This Section covers two methods – one for Windows and another for Linux and Mac.

Using the pywin32 package on Windows

The following code snippet shows how to print an Excel file on a physical printer. Ensure that Excel Application (Microsoft Excel) is installed and that you provide the correct path for the input file (you may need to provide the absolute path).

Alternatively, you may also want to print the Excel file to a file (say PDF). In this case, the following code should suffice.

Printing Excel Workbook into a file on Linux and Mac

Unlike Windows, Mac and Linux do not have a dedicated library for this. Instead, we will leverage the command line utilities for the purpose.

We also need an Excel application installed. In this case, we will use Libre Office with a command-line tool called libreoffice (by default).

To print an Excel File into a physical document, you will need to run the following command on the terminal

That will use the default printer. You can specify the printer with the –print-name command option.

You can also print the Excel workbook to a file using the –convert-to command option as follows

That will convert the employees.xlsx file into PDF. You can also pick other file extensions like EPUB or DOCX.

Lastly, you can run all these commands within Python using the os.system() function. For example,

Printing Excel Workbook Contents into Console

If you want to print the contents of an Excel file into the output console of your computer, you can use either of these methods.

Using pandas package

The package makes it easy to read and print an excel file. See below.

Note that that prints the contents of the first worksheet only. If you want to print the contents of a specified worksheet, you can use the “sheet_name” argument as follows (if you are using pandas version 0.21.0 or earlier, use “sheetname”)

Printing Excel file contents with openpyxl

The following code uses the package to print the contents of the employees.xlsx file cell by cell.

Conclusion

This article discussed different ways of printing an Excel Workbook using Python across different OS platforms.

The post covers printing an Excel file into a computer file (or a physical document) in the first part, and in the second part, we discussed how to print the file’s contents into the computer console.