可以用xlsxwriter 设置格式,注:只支持xlsx
import xlsxwriter #设置格式用 pip install xlsxwriter -i https://pypi.tuna.tsinghua.edu.cn/simple/
在:
writer=pd.ExcelWriter(os.path.join(path,‘统计表.xlsx’))
data1.to_excel(writer,sheet_name=“统计表”,startcol=0,startrow=0,index=False,header=True) #header=False无标
和
writer.save
writer.close()
间插入如下代码,设置宽度等格式
pd.io.formats.excel.header_style = None
# 设置格式
workbook1 = writer.book
worksheets = writer.sheets
worksheet1 = worksheets[u'统计表']
fmt = workbook1.add_format({"font_name": u"微软雅黑"})
worksheet1.set_column('A:J', 15, fmt)
format1 = workbook1.add_format({'bold': 1})
format2 = workbook1.add_format({'left':6})
font为字体, set_column为宽度,bold加粗…
‘bold’: 1, #字体加粗
‘fg_color’: ‘green’, #单元格背景颜色
‘align’: ‘center’, #对齐方式
‘valign’: ‘vcenter’, #字体对齐方式
set_row(row, height)方法,用于设定某一行单元格的行高
(row:指定行位置,起始下标为0;height:为float类型,设定行高,单位像素)
set_column(first_col, last_col, width)方法,用于设置一列或多列单元格的列宽
(first_col:整型,指定开始列位置,起始下标为0;last_col:整型,指定结束列位置,起始下标为0;width:float类型,设置列宽)
set_column(“first_col:last_col”, width)方法(first_col和last_col用英文字母表示列名,起始为A)
from openpyxl import load_workbook # 读取时导入这个
book = load_workbook(os.path.join(path,'基本信息表.xlsx')) #能写入已存在表中
writer = pd.ExcelWriter(os.path.join(path,'基本信息表.xlsx'), engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets) #不加入此行,新建表单写入
# if '统计表' in book.sheetnames:
# wbsheet=wb['统计表']
# wb.remove(wbsheet)
df1.to_excel(writer, '统计表')
writer.save()
在df.to_excel后设置格式
wb=load_workbook(os.path.join(path,‘基本信息表.xlsx’))
wbsheet = wb[‘统计表’]
wbsheet[“A1”].alignment = Alignment(horizontal=‘center’, vertical=‘center’) #对齐
wbsheet[“A1”].font = Font(name=‘微软雅黑’, size=20, bold=True, italic=False, color=colors.BLACK) #bold加粗,italic斜体
wbsheet.column_dimensions[“B"].width = 11.0 #B列宽度
“”"
bian = Side(style=‘medium’, color=‘000000’)
style:边框线的风格{‘dotted’,‘slantDashDot’,‘dashDot’,‘hair’,‘mediumDashDot’,
‘dashed’,‘mediumDashed’,‘thick’,‘dashDotDot’,‘medium’,
‘double’,‘thin’,‘mediumDashDotDot’}
border = Border(top=bian, bottom=bian, left=bian, right=bian)
top(上),bottom(下),left(左),right(右):必须是 Side类型
diagonal: 斜线 side类型
diagonalDownd: 右斜线 bool
diagonalDown: 左斜线 bool
“”"
fill = PatternFill(‘solid’, fgColor=‘CFCFCF’)
wbsheet[‘A1’].alignment = Alignment(horizontal=‘center’,vertical=‘center’)
wbsheet[‘A1’].fill = fill
“”"
horizontal:水平对齐(‘centerContinuous’, ‘general’, ‘distributed’,
‘left’, ‘fill’, ‘center’, ‘justify’, ‘right’)
vertical:垂直对齐(‘distributed’, ‘top’, ‘center’, ‘justify’, ‘bottom’)
“”"
“”"
name:字体名称
color:颜色通常是RGB或aRGB十六进制值
b(bold):加粗(bool)
i(italic):倾斜(bool)
shadow:阴影(bool)
underline:下划线(‘doubleAccounting’, ‘single’, ‘double’, ‘singleAccounting’)
charset:字符集(int)
strike:删除线(bool)
“”"