python–openpyxl
Introduction
openpyxl is a Python library to read/write Excel 2010 xlsx/xlsm/xltx/xltm files.
It was born from lack of existing library to read/write natively from Python the Office Open XML format.
function
Create a workbook and sheet
from openpyxl import Workbook
wb = Workbook()
# grab the active worksheet
ws = wb.active
You can create new worksheets using the Workbook.create_sheet()
method:
>>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
# or
>>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
# or
>>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position倒数第二
They are numbered in sequence (Sheet, Sheet1, Sheet2, …). You can change this name at any time with the
ws.title = "New Title"
you can get it as a key of the workbook:
>>> ws3 = wb["New Title"]
You can review the names of all worksheets Workbook.sheetname
attribute
>>> print(wb.sheetnames)
['Sheet2', 'New Title', 'Sheet1']
- 赋值
>>> c = ws['A4']
- 修改
>>> ws['A4'] = 4
在内存中创建工作表时,它不包含任何单元格。 它们是在首次访问时创建的。
- 保存
>>> wb = Workbook()
>>> wb.save('balances.xlsx')
# Data can be assigned directly to cells
ws['A1'] = 42
# Rows can also be appended
ws.append([1, 2, 3])
# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()
# Save the file
wb.save("sample.xlsx")