安装
pip install openpyxl==3.0.7
基本操作
import openpyxl
print(openpyxl.__version__)
wb = openpyxl.load_workbook('信息表.xlsx')
print(wb)
sheet1 = wb.sheetnames
print("sheet表名称:\n", sheet1)
sheet = wb['基本信息']
print(sheet)
print(wb.active)
cell = sheet['A4']
print(cell.value)
print(cell.row)
print(cell.column)
print(cell.coordinate)
print(sheet.cell(row=4, column=2).value)
for cell_row in sheet['A3':'D8']:
for cell in cell_row:
print(cell.coordinate, cell.value)
print(list(sheet.columns))
for cell in list(sheet.columns)[0]:
print(cell.value)
print('--------------------------')
print(sheet.max_row, sheet.max_column)
案例演示
import openpyxl, pprint
print('opening workbook...')
wb = openpyxl.load_workbook('人口统计简易表.xlsx')
sheet = wb['人口统计表']
print(wb.sheetnames)
countyData = {}
print('Reading rows...')
for row in range(2, sheet.max_row + 1):
state = sheet['B' + str(row)].value
county = sheet['C' + str(row)].value
pop = sheet['D' + str(row)].value
countyData.setdefault(state, {})
countyData[state].setdefault(county, {'tracts': 0, 'pop': 0})
countyData[state][county]['tracts']+=1
countyData[state][county]['pop']+=int(pop)
print('Writing results...')
resultFile = open('census2022.py','w')
resultFile.write('allData = '+pprint.pformat(countyData))
resultFile.close()
print('Done')
import os
import census2022
print(census2022.allData['AL']['FT'])
写入数据基本操作
import openpyxl
wb = openpyxl.Workbook()
print(wb)
print(wb.sheetnames)
sheet = wb.active
sheet.title = '跟进记录表'
print(wb.sheetnames)
wb.save('第一个工作蒲.xlsx')
wb = openpyxl.load_workbook('第一个工作蒲.xlsx')
wb.create_sheet(title='销售记录')
wb.create_sheet(index=1, title='养殖记录')
del wb['养殖记录']
print(wb.sheetnames)
wb.save('第一个工作蒲.xlsx')
sheet = wb['销售记录']
sheet['A1'] = 'hello'
sheet['B1'] = 'world'
wb.save('第一个工作蒲.xlsx')
定向修改数据
import openpyxl
wb = openpyxl.load_workbook('电子产品价格表.xlsx')
sheet = wb['Sheet1']
PRICE_UPDATES = {'苹果': 3,
'香蕉': 4,
'橘子': 5
}
for rowNum in range(2, sheet.max_row + 1):
productName = sheet.cell(row=rowNum, column=1).value
if productName in PRICE_UPDATES:
sheet.cell(row=rowNum, column=2).value = PRICE_UPDATES[productName]
wb.save('updateProductsSales.xlsx')
单元格样式制定
from openpyxl.styles import Font, PatternFill, Side, Border, Alignment
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet['A1'] = '字体'
sheet['A1'].font = Font(name='楷体', color='8470FF', size=12, italic=True, underline='single', b=True)
sheet['A2'].fill = PatternFill(patternType='solid', fgColor='8470FF')
sheet['A4'] = '效果1'
sheet['A5'] = '效果2'
s1 = Side(style='thin', color='8470FF')
s2 = Side(style='double', color='8470FF')
sheet['A4'].border = Border(top=s1)
sheet['A5'].border = Border(top=s2, bottom=s1, left=s2, right=s1)
sheet['B1'] = '效果1'
sheet['B2'] = '效果2'
sheet['B3'] = '效果3'
B1 = sheet['B1'].alignment = Alignment(horizontal='right')
B2 = sheet['B2'].alignment = Alignment(horizontal='center')
B3 = sheet['B3'].alignment = Alignment(horizontal='general')
wb.save('styles.xlsx')
数据过滤
from openpyxl.styles import Alignment
import openpyxl
wb = openpyxl.load_workbook('数据筛选表.xlsx')
sheet = wb['Sheet1']
sheet.auto_filter.ref = 'A1:D4'
sheet.auto_filter.add_filter_column(1, ['北京', '上海'])
sheet.auto_filter.add_sort_condition(ref='D2:D4', descending=True)
wb.save('数据筛选表.xlsx')
公式
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet['A1'] = 200
sheet['A2'] = 100
sheet['A3'] = '=SUM(A1:A2)'
wb.save('sum.xlsx')
wb = openpyxl.load_workbook('sum.xlsx',read_only=True)
sheet = wb.active
print(sheet['A3'].value)
单元格
import openpyxl
wb = openpyxl.load_workbook('行和列.xlsx')
sheet = wb['Sheet1']
print(sheet.row_dimensions)
print(sheet.column_dimensions)
sheet.row_dimensions[2].height = 50
sheet.column_dimensions['A'].width = 80
sheet.merge_cells('D1:G5')
sheet['D1'] = 'hello'
sheet.unmerge_cells('D1:G5')
wb.save('行和列.xlsx')