This article mainly describes the use of Python to manipulate Excel file instance code, the need for friends can refer to the following
The class library used
pip install openpyxl
Operation implementation
• Workbook actions
# coding:utf-8from OPENPYXL Import workbook# Create an Excel workbook WB = Workbook () # Open a workbook WB = Load_workbook (' test.xlsx ') # Save Workbook to Text Piece Wb.save (' save.xlsx ')
• Worksheet actions
# get current Sheet object ws = wb.active# get Worksheet object by sheet name ws = wb.get_sheet_by_name (' sheet ') # Gets the workbook all sheet object list WS = WB. Get_sheet_names () # Create a worksheet at the end of the workbook WS = Wb.create_sheet () # Create a worksheet in the first location WS = Wb.create_sheet (0) # Modify sheet name Ws.title = "New Sheet
• Data manipulation
# Use a cell # get cell contents according to index res = ws[' A4 ']# use the cell method to get cells res = Ws.cell (' A4 ') # or res = Ws.cell (row = 4, column = 1) # Create a 100*100 cell For I in range (1,101) to J in range (1,101) ws.cell (row = i, column = j) # Get multiple cells using slices cells = ws[' A1 ': ' D4 ']# using ite The R_rows () method obtains rows and columns T = touple (ws.iter_rows (' A1:d4 ')) # Use rows to get all rows T = ws.rows () # Use Columns () to get all columns T = Ws.columns ()
Summarize