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 thexlrdmodule, which is used to read the Excel (.xlsx) file.import openpyxl: This imports theopenpyxlmodule, which is used to write the Excel (.xlsx) file.wb = xlrd.open_workbook('excel_file.xlsx'): This opens the Excel (.xlsx) file using theopen_workbookmethod of thexlrdmodule.sheet = wb.sheet_by_index(0): This accesses the sheet by its index using thesheet_by_indexmethod of thexlrdmodule.wb = openpyxl.Workbook(): This creates a new Excel file using theWorkbookmethod of theopenpyxlmodule.sheet = wb.active: This accesses the active sheet using theactivemethod of theopenpyxlmodule.sheet['A1'] = 'Hello World': This sets the value of the cell atA1toHello World.wb.save('excel_file_2.xlsx'): This saves the Excel file using thesavemethod of theopenpyxlmodule.
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I upgrade my Python Scipy package?
- How can I use Python and SciPy to read and write WAV files?
- How do I use the trapz function in Python SciPy?
- How do I rotate an image using Python and SciPy?
- How do I use Python Scipy's Odeint function?
- How do I install SciPy for Python?
See more codes...