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 and SciPy to find the zeros of a function?
- How can I install and use SciPy on Ubuntu?
- How do I create a numpy array of zeros using Python?
- How can I use Python and Numpy to zip files?
- How do I use Scipy zeros in Python?
- How can I use Python SciPy to fit a model?
- How can I use Python Scipy to zoom in on an image?
- How can I use Python and Numpy to parse XML data?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
See more codes...