1. Installation
Installation can be achieved with the following command
pip install openpyxl # pip
conda nstall openpyxl # conda
2. Main usage
To start using openpyxl without creating a file in the filesystem, import the Workbook class
from openpyxl import Workbook
wb = Workbook()
There is at least one workbook (sheet) in a worksheet, which is activated through the Workbook.active property
ws = wb.active # 默认是第一个sheet
If you want to create a new sheet, create it through the Workbook.create_sheet method
ws1 = wb.create_sheet("Mysheet") # 在最后插入, 默认是这个
ws1 = wb.create_sheet("Mysheet", 0) # 在第一的位置插入
ws1 = wb.create_sheet("Mysheet", -1) # 在倒数第二的位置插入
ws1 = wb.create_sheet(title="MyName") # 可通过title设置sheet名字
When the sheet is named, the name is the key of the sheet, and the sheet can be extracted by using the key
ws = wb['MyName']
Use the Workbook.sheetname property to view the names of all sheets in the table
names = wb.sheetname
Traverse the sheets in the worksheet
for sheet in wb:
print(sheet.title)
write cell
- Use the index to locate the cell
ws['A1'] = 42
- Use list data
ws.append([1, 2, 3])
- Write using the cell() method
for i in range(1, 100):
for j in range(1, 100):
ws.cell(row=i, col=j, value=i*j) # 其中value的值可以根据需要进行更改
Export the table we created
wb.save('balances.xlsx')