python-scipyHow do I use Python Numpy to read and write Excel (.xlsx) files?
Using Python Numpy to read and write Excel (.xlsx) files is relatively easy. To do this, you will need to import the xlrd
and openpyxl
modules.
Example code
import xlrd
import openpyxl
# Read excel file
wb = xlrd.open_workbook('excel_file.xlsx')
sheet = wb.sheet_by_index(0)
# Write excel file
wb = openpyxl.Workbook()
sheet = wb.active
sheet['A1'] = 'Hello World'
wb.save('excel_file_2.xlsx')
The xlrd
module is used to read the Excel (.xlsx) file, while the openpyxl
module is used to write the Excel (.xlsx) file. The open_workbook
method of the xlrd
module is used to open the Excel file, while the Workbook
method of the openpyxl
module is used to create a new Excel file. The sheet_by_index
method of the xlrd
module is used to access the sheet by its index, while the active
method of the openpyxl
module is used to access the active sheet. Finally, the save
method of the openpyxl
module is used to save the Excel file.
Code explanation
import xlrd
: This imports thexlrd
module, which is used to read the Excel (.xlsx) file.import openpyxl
: This imports theopenpyxl
module, which is used to write the Excel (.xlsx) file.wb = xlrd.open_workbook('excel_file.xlsx')
: This opens the Excel (.xlsx) file using theopen_workbook
method of thexlrd
module.sheet = wb.sheet_by_index(0)
: This accesses the sheet by its index using thesheet_by_index
method of thexlrd
module.wb = openpyxl.Workbook()
: This creates a new Excel file using theWorkbook
method of theopenpyxl
module.sheet = wb.active
: This accesses the active sheet using theactive
method of theopenpyxl
module.sheet['A1'] = 'Hello World'
: This sets the value of the cell atA1
toHello World
.wb.save('excel_file_2.xlsx')
: This saves the Excel file using thesave
method of theopenpyxl
module.
Helpful links
More of Python Scipy
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use the trapz function in Python SciPy?
- How do I create a 2D array of zeros using Python and NumPy?
- How to use Python, XML-RPC, and NumPy together?
- How do I calculate variance using Python and SciPy?
- How can I use Python and Numpy to parse XML data?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I download a Python Scipy .whl file?
- How do I use the numpy vstack function in Python?
See more codes...