python如何简单操作Excel
1.openpyxl读Execl文件
import openpyxl
wb = openpyxl.open('files/data.xlsx')
names = wb.sheetnames
print(names)
a_sheet = wb.active
print(a_sheet)
student_s = wb['student']
print(student_s)
teacher_s = wb['teacher']
print(teacher_s)
mr = student_s.max_row
mc = student_s.max_column
print(mr, mc)
cell1 = student_s.cell(1, 2)
cell2 = student_s.cell(3, 1)
print(cell1.value)
print(cell2.value)
print('---------------------------------------华丽的分割线------------------------------------')
stu = []
row = 5 + 1
for col in range(1, mc+1):
stu.append(student_s.cell(row, col).value)
print(stu)
print('---------------------------------------华丽的分割线------------------------------------')
genders = []
col = 4
for row in range(2, mr + 1):
value = student_s.cell(row, col).value
genders.append(value)
print(genders)
print('---------------------------------------华丽的分割线------------------------------------')
teacher_s = wb['teacher']
t_mc = teacher_s.max_column
t_mr = teacher_s.max_row
for row in range(1, t_mr+1):
row_data = []
for col in range(1, t_mc+1):
value = teacher_s.cell(row, col).value
row_data.append(value)
print(row_data)
2.Execl写操作(openpyxl)
import openpyxl
import os
if os.path.exists('files/data2.xlsx'):
wb1 = openpyxl.open('files/data2.xlsx')
else:
wb1 = openpyxl.Workbook()
if 'student' in wb1.sheetnames:
print('获取学生表')
student = wb1['student']
else:
print('创建学生表')
student = wb1.create_sheet('student')
if 'Sheet' in wb1.sheetnames:
wb1.remove(wb1['Sheet'])
student.cell(1, 3).value = '李四'
student.cell(1, 1).value = '老王'
student.cell(1, 2).value = None
wb1.save('files/data2.xlsx')
3.设置样式(openpyxl)
import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
wb = openpyxl.open('files/data.xlsx')
sheet = wb.active
sheet.column_dimensions['A'].width = 25
sheet.column_dimensions['B'].width = 30
sheet.row_dimensions[1].height = 30
for x in range(2, 5):
sheet.row_dimensions[x].height = 25
font1 = Font(
name='黑体',
color='643850',
size=15,
)
for row in range(2, 5):
sheet.cell(row, 1).font = font1
fill1 = PatternFill(
fill_type='solid',
start_color='FAFAD2',
end_color='FF7F50'
)
sheet.cell(1, 1).fill = fill1
ag1 = Alignment(
vertical='center',
horizontal='center'
)
sheet.cell(1, 2).alignment = ag1
side1 = Side(
border_style='medium',
color='800080'
)
side2 = Side(
border_style='mediumDashed',
color='ff0000'
)
border1 = Border(bottom=side1, top=side1, left=side2, right=side2)
sheet.cell(2, 4).border = border1
wb.save('files/data.xlsx')