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 create a 2D array of zeros using Python and NumPy?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I create a zero matrix using Python and Numpy?
- How do I create a numpy array of zeros using Python?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and SciPy to implement an ARIMA model?
- How do I create a numpy array of zeros using Python?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Scipy zeros in Python?
- How do I use Python Scipy to perform a Z test?
See more codes...