python 单元格内文字颜色格式

xlsxwriter

from xlsxwriter.workbook import Workbook


workbook = Workbook(filename='shishi.xlsx')
worksheet = workbook.add_worksheet()
red_color = workbook.add_format({'color': 'red', 'bold': True})
"""构建字体颜色"""
wl = ['abcd', 'efgh']
# 有颜色用 富文本      
worksheet.write_rich_string(0, 0, wl[0], red_color, wl[1])   要哪个字符串变颜色,就把颜色放在哪个的前面
# 没颜色直接写入
worksheet.write(0, 1, 'ccss')
worksheet.write(0, 2, 3)
worksheet.write_row('A1', wl, red_color)   写入一整行 从哪个单元格开始就写哪个单元格
workbook.close()


openpyxl

from openpyxl import Workbook
from openpyxl.styles import Font  # 导入字体模块


wb = Workbook()
sheet = wb.active
Color = 'ffc7ce'

font = Font(u'等线', size=11, bold=False, italic=False, strike=False, color=Color)  # 设置字体样式
sheet.cell(row=i, column=1, value="哈哈").font = font # 序列
sheet.merge_cells('A1:B1')
wb.save('shishi.xlsx')


def cell_format():
    from openpyxl.styles import Border, Side, Font, Alignment, NamedStyle, PatternFill
    format_all = {}
    # 设置边框
    border_type = Side(border_style='thin', color='000000')
    border = Border(left=border_type, right=border_type, top=border_type, bottom=border_type)
    # 设置对齐
    align = Alignment(horizontal='center', vertical='center', wrap_text=False)
    # 设置字体颜色大小
    font = Font(bold=False, name='等线', color="000000")  # size=11,

    # 设置背景色
    title_fill = PatternFill(fill_type='solid', start_color='C0C0C0')  # 灰

    title_format = NamedStyle(name='title_format', border=border, fill=title_fill, alignment=align, font=font)
    normal_format = NamedStyle(name='normal_format', border=border, alignment=align, font=font)

    format_all['title_format'] = title_format
    format_all['normal_format'] = normal_format
    return format_all

format_all = cell_format()  # 调用
for cell in list(ws.rows)[0]:
    cell.style = format_all['title_format']
for row in ws.iter_rows(min_row=2):
    for cell in row:
        cell.style = format_all['normal_format']

# 设置行高
ws.row_dimensions[1].height = 20
# 设置列宽
from openpyxl.utils import get_column_letter
for i in range(1, ws.max_column + 1):
    if i == 1:
        ws.column_dimensions[get_column_letter(1)].width = 8
    else:
        ws.column_dimensions[get_column_letter(i)].width = 18
    

xlwt

import xlwt


content_font = xlwt.Font()
# content_font.name = '宋体'
# content_font.height = 20 * 12  # 字体大小  20位衡量单位
# content_font.bold = False  # 加粗
# content_font.underline = False  # 下划线
# content_font.italic = True  # 斜体
content_font.colour_index = 0x0A
wl = ['abcd', 'efgh']
workbook = xlwt.Workbook(encoding = 'utf-8')
sheet = workbook.add_sheet('sheet1')
sheet.write_rich_text(0, 0, [[wl[0], content_font], wl[1]])
workbook.save('shishi.xlsx')

你可能感兴趣的:(python 单元格内文字颜色格式)