本篇文章主要介绍用如何用 python 将 xlsx 的某 sheet 或指定 Range 转换为 html 格式
如何将Excel表格中的指定数据区域(如某个sheet或特定单元格范围)转换为HTML格式?
方法一:使用pandas+to_html()(超简单!)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
import pandas as pd
# 读取Excel文件 🏁
df = pd.read_excel('data.xlsx', sheet_name='Sheet1') # 可以指定sheet名或索引
# 转换为HTML (超简单!)
html = df.to_html(classes='my-table', index=False) # 不显示索引
print(html)
# 保存为HTML文件 💾
with open('output.html', 'w', encoding='utf-8') as f:
f.write("""
<!DOCTYPE html>
<html>
<head>
<style>
.my-table {
border-collapse: collapse;
width: 100%;
}
.my-table th, .my-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.my-table th {
background-color: #f2f2f2;
}
.my-table tr:nth-child(even) {
background-color: #f9f9f9;
}
</style>
</head>
<body>
""" + html + """
</body>
</html>
""")
|
指定范围小技巧 ✨
1
2
3
4
5
|
# 只转换B2:D10范围
df = pd.read_excel('data.xlsx', sheet_name='Sheet1',
header=1, # 从第2行开始(0-based)
usecols="B:D", # B到D列
nrows=8) # 读取8行(B2:D10)
|
方法二:使用openpyxl精确控制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
from openpyxl import load_workbook
def excel_range_to_html(filepath, sheet_name, cell_range):
wb = load_workbook(filepath)
ws = wb[sheet_name]
# 获取范围数据 🎯
rows = []
for row in ws[cell_range]:
row_data = []
for cell in row:
row_data.append(str(cell.value) if cell.value is not None else "")
rows.append(row_data)
# 生成HTML表格 🏗️
html_table = "<table border='1'>\n"
for row in rows:
html_table += " <tr>\n"
for value in row:
html_table += f" <td>{value}</td>\n"
html_table += " </tr>\n"
html_table += "</table>"
return html_table
# 使用示例:转换Sheet1的A1到C5范围
html_output = excel_range_to_html('data.xlsx', 'Sheet1', 'A1:C5')
with open('table_part.html', 'w') as f:
f.write(html_output)
|
方法三:使用xlsx2html专业转换库
1
2
3
4
5
6
7
8
|
# 先安装:pip install xlsx2html
from xlsx2html import xlsx2html
# 转换整个sheet 🔄
xlsx2html('data.xlsx', 'output_full.html', sheet='Sheet1')
# 转换指定范围 (需要修改库代码或结合openpyxl)
# 替代方案:先拷贝范围到新sheet,再转换
|
方法四:Excel VBA方法(Windows特供)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import win32com.client
def excel_to_html_vba(input_path, output_path, sheet_name):
excel = win32com.client.Dispatch("Excel.Application")
workbook = excel.Workbooks.Open(input_path)
sheet = workbook.Sheets(sheet_name)
# 使用VBA的SaveAs方法
sheet.SaveAs(output_path, 44) # 44是HTML格式
workbook.Close(False)
excel.Quit()
# 使用示例
excel_to_html_vba('data.xlsx', 'output_vba.html', 'Sheet1')
|
🌈 样式美化小贴士
- 表格样式:在
<style>
标签中添加CSS
1
2
3
4
5
6
7
8
9
|
table {
border-collapse: collapse;
font-family: Arial;
}
th {
background-color: #4CAF50;
color: white;
}
tr:hover {background-color: #f5f5f5;}
|
- 响应式表格:
1
2
3
|
<div style="overflow-x:auto;">
<!-- 你的表格 -->
</div>
|
- 添加标题:
1
|
html = f"<h2>{sheet_name}报表</h2>\n" + df.to_html()
|
- 格式化数字:
1
|
pd.options.display.float_format = '{:,.2f}'.format # 两位小数
|
💡 专业建议
- 处理大数据时建议分页显示
- 含公式的单元格需要特殊处理(
.value
vs .formula
)
- 合并单元格需要额外处理(openpyxl的
merged_cells
属性)
- 考虑添加导出时间水印:
1
2
|
from datetime import datetime
html = f"<!-- 生成时间:{datetime.now()} -->\n" + html
|
哪个方法最适合你?快试试看吧!(≧∇≦)ノ
有问题欢迎留言讨论~ 🎤