如何用Python转换Excel表格为HTML并保留格式(边框、背景色等)
解决Excel转HTML保留样式的问题
pandas的to_html()方法只负责导出数据,不会读取Excel里的单元格样式(背景色、字体加粗、对齐方式这些),所以得换方式处理,下面给两种可行的方案:
方案一:用openpyxl读取样式,手动生成HTML
openpyxl可以读取Excel文件的单元格样式信息,我们可以基于它来构建带inline CSS的HTML表格,确保样式保留。
步骤:
- 安装依赖:
pip install openpyxl
- 示例代码:
from openpyxl import load_workbook def excel_to_html_with_style(excel_path, html_path): wb = load_workbook(excel_path, data_only=True) ws = wb.active # 初始化HTML内容 html_content = ['<table style="border-collapse: collapse; width: 100%;">'] for row_idx, row in enumerate(ws.iter_rows(), start=1): html_content.append('<tr>') for cell in row: # 基础样式:边框 style = 'border: 1px solid #000; ' # 对齐方式:居中 style += 'text-align: center; vertical-align: middle; ' # 前3行设置灰色背景+加粗 if row_idx <= 3: style += 'background-color: #f0f0f0; font-weight: bold; ' # 如果单元格有自定义背景色(读取Excel里的填充色) if cell.fill.fgColor.rgb != '00000000': style += f'background-color: #{cell.fill.fgColor.rgb[2:]}; ' # 如果单元格字体加粗 if cell.font.bold: style += 'font-weight: bold; ' # 添加单元格内容和样式 cell_value = cell.value if cell.value is not None else '' html_content.append(f'<td style="{style}">{cell_value}</td>') html_content.append('</tr>') html_content.append('</table>') # 写入HTML文件 with open(html_path, 'w', encoding='utf-8') as f: f.write('\n'.join(html_content)) # 调用示例 excel_to_html_with_style('你的表格.xlsx', '结果.html')
说明:
data_only=True是读取单元格的计算结果,而非公式- inline CSS确保样式直接作用在单元格上,避免外部样式表丢失
- 代码同时处理了Excel原有的样式和你要求的前3行灰色加粗+全局居中,优先保留Excel原样式
方案二:用StyleFrame库快速实现
StyleFrame是封装了pandas和openpyxl的库,能直接处理带样式的表格转换,代码更简洁。
步骤:
- 安装依赖:
pip install styleframe
- 示例代码:
from styleframe import StyleFrame, Styler def excel_to_html_styleframe(excel_path, html_path): # 读取Excel文件,保留原有样式 sf = StyleFrame.read_excel(excel_path, read_style=True) # 设置全局样式:所有单元格居中+边框 global_styler = Styler( horizontal_alignment='center', vertical_alignment='center', border_type='thin' ) sf.apply_style_by_indexes(sf.index, global_styler) # 给前3行设置灰色背景+加粗 header_styler = Styler( bg_color='#f0f0f0', bold=True ) sf.apply_style_by_indexes(sf.index[:3], header_styler) # 导出为HTML,样式嵌入标签内 sf.to_html(html_path, inline_styles=True) # 调用示例 excel_to_html_styleframe('你的表格.xlsx', '结果.html')
说明:
read_style=True会读取Excel原有的样式inline_styles=True确保样式嵌入到HTML标签里,打开就能看到效果- 可以灵活调整样式,比如修改背景色、字体大小等
内容的提问来源于stack exchange,提问作者userfb
相关产品推荐
相关产品推荐

