openpyxl is a python library for reading and writing Excel 2010 xlsx files.
openpyxl official document: https://openpyxl.readthedocs.io/en/stable/
First, the installation package
pip3 install openpyxl
Second, create Excel, write data
from openpyxl Import the Workbook # Create the Workbook, and creates a default table empty, entitled: Sheet WB = the Workbook () # Get Default Sheet WS1 = wb.active # Set Sheet Name ws1.title = ' Sheet1 ' # Write Single cell WS1 [ ' A1 ' ] = ' title bar. 1 ' WS1 [ ' Bl ' ] = ' title bar 2 ' # written in a plurality of cells (written from the next line of data) ws1.append ([ ' John Doe ' , 80 ]) ws1.append ([ ' John Doe' , 90 ]) # create a new sheet, you can specify the name ws2 = wb.create_sheet ( ' Sheet2 ' ) # copy Sheet1, the new name for the sheet Copy Sheet1 ws3 = wb.copy_worksheet (wb [ ' Sheet1 ' ]) # print all table name Print (wb.sheetnames) # save wb.save ( ' 1.xlsx ' )
The results Excel reads as follows:
Third, read Excel data
1.xlsx read data created above
from openpyxl Import the Workbook from openpyxl Import load_workbook WB = load_workbook ( ' 1.xlsx ' ) # speculation format type wb.guess_types = True WS1 = wb.active Print ( " number of rows " , ws1.max_row) Print ( " total number of columns ' , ws1.max_column) Print ( ' --- value acquiring single cell --- ' ) Print (WS1 [ ' A1 ' ] .Value) Print(WS1 [1] [0] .Value) # where A1 is the value from the row index 1, index column counting from 0 Print ( ' --- get values for all the single --- ' ) for Cell in WS1 [ ' a ' ]: Print (Cell.Value) Print ( ' --- get the value of a plurality of columns (by slicing) --- ' ) # If the range is larger than the actual, real as AB only two, designated a: B, the acquisition result returned None, and C is the column and later .columns .rows acquired for column in WS1 [ ' A: B ' ]: for Cell in column: Print (Cell.Value) Print ( '--- get the value of all the columns --- ' ) for column in ws1.columns: # can also be used ws1.iter_cols () for the Cell in column: Print (Cell.Value) Print ( ' --- get the value of a row --- ' ) for Cell in WS1 [. 1 ]: Print (Cell.Value) Print ( ' --- obtain the value of a plurality of rows (by slicing) --- ' ) for row in WS1 [. 1: 2 ]: for the Cell in Row: Print (Cell.Value) Print ( ' --- get the value of all rows --- ' ) for Row in ws1.rows: # can also be used ws1.iter_rows () for the Cell in Row: Print (Cell.Value)