python操作excel

# pip install openpyxl安装
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Side

# 创建一个新的工作簿
wb = Workbook()
# 选择活动工作表
ws = wb.active
# 设置列宽
# 设置 A 列宽度为 20
ws.column_dimensions['A'].width = 20
# 设置 B 列宽度为 30
ws.column_dimensions['B'].width = 30
# 设置 C 列宽度为 30
ws.column_dimensions['C'].width = 30

# 在工作表中写入数据
ws['A1'] = '标题 1'
ws['B1'] = '标题 2'
ws['A2'] = '数据 1'
ws['B2'] = '数据 2666'
ws['C1'] = '标题 1'
ws['C2'] = '标题 2'

# 设置第一行高18
# ws.row_dimensions[1].height = 18
# 设置所有行高为 18,必须写底部
for row in ws.iter_rows():
    ws.row_dimensions[row[0].row].height = 25

# 设置水平居中,单个
# alignment = Alignment(horizontal='center')
# ws['A1'].alignment = alignment
# 设置所有单元格垂直居中+水平居中
for row in ws.iter_rows():
    for cell in row:
        # horizontal垂直居中,vertical水平居中
        alignment = Alignment(horizontal='center', vertical='center')
        cell.alignment = alignment

# 设置 B 列所有单元格水平靠左对齐,vertical水平居中,min_col那一列开始,max_col那一列结束
for row in ws.iter_rows(min_row=1, min_col=3, max_col=3):
    for cell in row:
        alignment = Alignment(horizontal='left', vertical='center')
        cell.alignment = alignment

# 设置第一行所有单元格水平和垂直都居中
for cell in ws[1]:
    alignment = Alignment(horizontal='center', vertical='center')
    cell.alignment = alignment

# 冻结首行
# ws.freeze_panes = 'A2'
# # 冻结首列
# ws.freeze_panes = 'B1'
# 冻结首行和首列
ws.freeze_panes = 'B2'

# 去掉网格线显示
sheet_view = ws.sheet_view
sheet_view.showGridLines = False

# 设置黑边框
thin_border = Border(left=Side(style='thin', color='000000'),
                     right=Side(style='thin', color='000000'),
                     top=Side(style='thin', color='000000'),
                     bottom=Side(style='thin', color='000000'))
for row in ws.iter_rows():
    for cell in row:
        cell.border = thin_border

# 保存工作簿
wb.save('dade/dade.xlsx')

python操作excel_第1张图片

你可能感兴趣的:(python,excel,开发语言)