python openpyxl 操作excel

 

openpyxl 是从1开始计数,遍历操作时请用1为起始点,且总数加一,例:for i in range(1, n+1)

 

单元格样式

所需导入模块

from openpyxl.styles import Alignment, Font, Border, Side,PatternFill

样式

    # 设置边框线
    align = Alignment(horizontal='center', vertical='center', wrap_text=True)
    # 设置边框线样式
    top = Side(border_style='thin', color='000000')
    bottom = Side(border_style='thin', color='000000')
    left = Side(border_style='thin', color='000000')
    right = Side(border_style='thin', color='000000')
    border = Border(top=top, bottom=bottom, left=left, right=right)
    # 设置字体
    font = Font(u'宋体', size='10.5')
    # 合并单元格 所输行列是会一起包含合并
    # sheet.merge_cells("A1:A3")
    # sheet.merge_cells(start_row=1, end_row=3, start_column=10, end_column=11)
    # 设置填充颜色
    fille = PatternFill('solid', fgColor="FF00FF")

单元格设置

        # 字体
        # sheet.cell(i, 4).font = font
        # sheet[f'D{i}'].font = font

        # 填充颜色
        # sheet.[f'D{i}'].fill = fille
        # sheet.cell(1, 1, "洋红色").fill = fille

        # 对齐方式
        # sheet.cell(i, 4).alignment = align
        # sheet[f'D{i}'].alignment = align

        # 边框
        # sheet.cell(i, 6).border = border
        # sheet[f'E{i}'].border = border

        # 行高
        # sheet.row_dimensions[i + 1].height = cell_height
        # 列宽 i为必须字母,不能是数字
        # sheet.column_dimensions[i].width = 20

 

参考来源:第1节,使用openpyxl 读取excel文件 | 酷python (coolpython.net)

posted @ 2023-05-15 21:05  记录——去繁就简  阅读(84)  评论(0)    收藏  举报