Openpyxl python is a common repository for common template Excel format and performs data read and write operations.
installation
installation
pip install openpyxl
pillow: Need to use the images (jpeg, png, bmp, ...) in the file, you need to install pillow library.
Note: Please close the excel files need to operate during a write operation, write or unsuccessful
Xlsx load operation content
Loading external excel xlsx steps of:
loading xlsx file, get the file handle for the workbook
from openpyxl import load_workbook
wb = load_workbook('test.xlsx')
print(wb.get_sheet_names())
# ['Sheet2', 'New Title', 'Sheet1']
Gets the designated column
wb = load_workbook(pwd)
ws = wb['action']
cols = ws['C']
for cell in range(2, ws.max_row):
v = v2[cell].value
if v is None: # 去掉空行
continue
print(v)
max_row is inclusive of all the empty rows of empty rows to None
New workbook in memory
Create a workbook
Started openpyxl, there is no need to create a file on the file system.
Just import Workbook class and start using it. Wordbook can be thought of as an excel file.
from openpyxl import Workbook
wb = Workbook()
After the workbook is created at the very least you want to create a worksheet. useopenpyxl.workbook.Workbook.active()
ws = wb.active
The method uses _active_sheet_index property, default setting 0
Create a worksheet
Use openpyxl.workbook.Workbook.create_sheet()
to create a new worksheet
ws1 = wb.create_sheet("new_sheet_1") # 新建sheet,插入到最后(默认)
ws2 = wb.create_sheet("new_sheet_2", 0) # 插入到最开始的位置
Specifies the name of the worksheet
When you do not specify sheet name, according to the sheet, sheet1, sheet2 automatic growth
ws3 = wb.create_sheet()
Custom worksheet name, by specifying the name of the property title, set the name of the sheet
ws3.title = "new_sheet_3"
Now all sheetname output wb view
through openpyxl.workbook.Workbook.sheetnames()
output wb Now all sheetname
print wb.get_sheet_names()
print(wb.sheetnames)
cycle
for sheet in wb:
print(sheet.title)
Specifies the worksheet tab button color
The new sheet tab color is white, you can additionally specify color sheet tab button
ws3.sheet_properties.tabColor = "1072BA"
Activate a worksheet
Name of the active worksheet by using a sheet
as a key workbook name in
ws3 = wb["new_sheet_3"]
By _active_sheet_index
activating a sheet use
wb._active_sheet_index = 1 # 获取第二个sheet
Create a copy of the worksheet
Use openpyxl.workbook.Workbook.copy_worksheet()
to create a copy of the worksheet
source = wb.active
target = wb.copy_worksheet(source)
You can only copy cell and style. The workbook can not be copied between worksheets.
Operation Cell
When a worksheet is created in memory, is not included cells, the cells are created when you first visit
the cell can be seen as key worksheet by key access to data in a cell
c = ws['A3'] # 访问单元格,不存在则会自动创建一个
print c.value
ws['A4'] = 'a4 value' # 指定单元格的值
print ws['A4'].value
d = ws.cell(row=4, column=2, value='通过cell指定') # 通过row column数字指定
print d.value
Circulating cells created in memory
Without specifying its value can be created in memory
for i in range(1, 10):
for j in range(1, 10):
ws.cell(row=i, column=j)
Many cells designated by slicing Ranges
cell_range = ws['A1':'C2']
Ranges rows or columns can also be
print ws['C']
print ws['C:D']
print ws[10]
print ws[5:10]
You can also use iter_rows () specified line -> line, cut-off column
for row in ws.iter_rows(min_row=1, max_row=2, max_col=3):
for c in row:
print(c)
iter_cols () the specified column -> columns, cut-off line
for row in ws.iter_rows(min_col=1, max_col=3, max_row=20):
for c in row:
print(c)
Use index
Use directly
for row in ws.iter_rows(min_row=2, max_row=5, max_col=6):
for index, c in enumerate(row):
row[0].value = "aaa"
row[1].value = "bbb"
row[2].value = "ccc"
Through all the files of a row or column
ws['C9'] = 'hello world'
tuple(ws.rows) # 转化成tuple方便for in操作
tuple(ws.columns)
save document
wb = Workbook()
wb.save("assets/sample.xlsx")
This existing file overwrites without warning.
All operations are to see the need to save to excel
Save as template
Specifies the property as_template=True
, you can save the document as a template .xltx
wb = load_workbook('document.xlsx')
wb.template = True
wb.save('document_template.xltx')
Or the property is set to False (the default), save it as a file:
wb = load_workbook('document_template.xltx')
wb.template = False
wb.save('document.xlsx', as_template=False)
Using the formula
wb = load\_workbook\('assets/sample.xlsx'\)
ws = wb.active
ws\["A5"\] = "=SUM\(2, 1\)"
wb.save\("assets/sample.xlsx"\)