Python Parsing Excel - Openpyxl
Python parsing excel.foreword
Some time ago, the work revolved around AWS's autoscaling, writing terraform, modifying AWS's configuration, and then writing a lambda in python. It was this time that gave me an opportunity to learn python. (I wanted to learn it myself, but the work has been put on hold since it was not used).
After I finished learning Python , I thought about writing something in python and applying it for real, so I started to try how to use python to parse excel.
code can be directly viewed in excelResolve.py in
https://github.com/luckypoison/pythonNote . In the concept of excel, the largest unit is the workbook . It can be said that it is a mapping of the entire excel, and then there are multiple sheets in a workbook. , in each sheet, each cell is a cell , which is the smallest cell we can get.
Since we are using openpyxl , we need to import this package first:
# Introduce opnepyxl to parse excel
import openpyxl as xl
We can get the workbook like this:
# excel_name is the string of the file, if the path is not specified, it refers to the current path
xl.load_workbook ( excel_name ) _
We can get the sheet like this
# excel_workbook is the instance of the workbook just obtained, sheet_name is the name of the sheet in excel, and "Sheet1" in the case of a new one
excel_workbook [ sheet_name ]
We can get the cell like this
# excel_sheet is the sheet instance just obtained, cell_position is a string (if it is the first row and first column, the position is a1)
excel_sheet [ cell_position ]
Get the value in the cell
excel_sheet [ cell_position ] .value
Modify the value in the cell
excel_sheet [ cell_position ]. value = modified value
# Don't forget the save file at the end
excel_workbook.save ( 'filename' )
Tips: Remember to save the file after modification, it is equivalent to save as. I tried if the name of save as is the same as the name of the original file, the original file does not change, so save the file with another name.