用 Python 给 Excel 表格截图(20250207)

server/2025/2/9 5:22:12/

我搜索了网络上的方案,感觉把 Excel 表格转换为 HTML 再用 platwright 截图是比较顺畅的路径,因为有顺畅的工具链。如果使用的是 Windows 系统则不需要阅读此文,因为 win32com 库更方便。这篇文章中 Excel 转 HTML 的方案,主要弥补了网上其他方案中存在合并单元格的情况。代码为智谱清言帮助生成,有些变量控制还是需要自己改一下。


from openpyxl import load_workbook
from openpyxl.styles import Font, Border, Side, Alignment
from playwright.sync_api import sync_playwright
from datetime import datetime# 打开浏览器并截图
def capture_table_screenshot( url, output_file, table_selector):with sync_playwright() as p:browser = p.chromium.launch(headless=False)page = browser.new_page()# 注意这里需要加协议page.goto("file://" + url)# 等待表格元素加载完成page.wait_for_selector(table_selector)page.wait_for_timeout(1000)# 对表格元素进行截图table_element = page.locator(table_selector)table_element.screenshot(path=output_file)browser.close()# 默认合并单元格的文本内容是放在左上单元格的,如果不是,需要专门程序处理。
# 边框样式默认为1px solid
def read_excel(file_path):# data_only 将 Excel 表格里的公式计算成数值读取出来。wb = load_workbook( filename=file_path, data_only=True)ws = wb.active  # 读取活动工作表data = []merges = []  # 用于存储合并单元格的信息cell_styles = []# 读取合并单元格信息for merged_range in ws.merged_cells.ranges:start_row, start_col = merged_range.min_row, merged_range.min_colend_row, end_col = merged_range.max_row, merged_range.max_colmerges.append((start_row-1, start_col-1, end_row-1, end_col-1))for row in ws.iter_rows():row_data = []row_styles = []for cell in row:print(f"当前单元格的坐标:{cell.coordinate}")if cell.coordinate in ws.merged_cells.ranges:# 跳过合并单元格中的非起始单元格continue            if cell.value is not None:print(f"单元格的值:{cell.value}")row_data.append(str(cell.value))                else:row_data.append('')  # 空单元格填充空字符串# 读取单元格样式,提供默认值font = cell.font if cell.font else Font()border = cell.border if cell.border else Border()alignment = cell.alignment if cell.alignment else Alignment()print(f"单元格字体颜色:{font.color.index}")print(f"单元格边框样式:{border.top.style}")cell_style = {'font': {'name': font.name if font.name else 'Arial','size': font.size if font.size else 12,'bold': font.bold if font.bold else False,'italic': font.italic if font.italic else False,'color': font.color.rgb if font.color and font.color.rgb else '#000000'},'border': {'top': '1px solid' if border.top and border.top.style else None,'left': '1px solid' if border.left and border.left.style else None,'right': '1px solid' if border.right and border.right.style else None,'bottom': '1px solid' if border.bottom and border.bottom.style else None},'alignment': {'horizontal': alignment.horizontal if alignment.horizontal else None,'vertical': alignment.vertical if alignment.vertical else None}}row_styles.append(cell_style)print(f"转换后的单元格样式:{cell_style}")data.append(row_data)cell_styles.append(row_styles)      return data, merges, cell_styles# 该处默认只有同一行合并多列的情况。如果合并单元格占了两行,需要另外的处理。
def generate_html_table(data, merges, cell_styles):print(f"合并单元格的信息:{merges}")html = "<table style='border-collapse: collapse;'>\n"for row_idx, row in enumerate(data):print("-"*20)print(f"当前行的数据:{row}")html += "<tr>\n"# 设置一个跳过非首个合并单元格的标记skip_next_cell = 0for col_idx,cell in enumerate(row):if skip_next_cell > 0:skip_next_cell -= 1continue# 行号、列号从0开始print(f"当前单元格的值:{cell},行号:{row_idx},列号:{col_idx}")# 如果当前单元格为1行4列,则修改cell值if row_idx == 1 and col_idx == 4:# 获取今天的日期today = datetime.today()cell = formatted_date_no_leading_zeros = "截止 " + today.strftime("%-m 月 %-d 日")print(f"修改后的单元格值:{cell}")# 去除单元格样式style = cell_styles[row_idx][col_idx]if style:                font_style = f"font-family:{style['font']['name']}; font-size:{style['font']['size']}pt; " \f"font-weight:{'bold' if style['font']['bold'] else 'normal'}; " \f"font-style:{'italic' if style['font']['italic'] else 'normal'};"border_style = f"border-top:{style['border']['top']}; " \f"border-left:{style['border']['left']}; " \f"border-right:{style['border']['right']}; " \f"border-bottom:{style['border']['bottom']};"alignment_style = f"text-align:{style['alignment']['horizontal']}; " \f"vertical-align:{style['alignment']['vertical']};"if (row_idx, col_idx) in [(m[0], m[1]) for m in merges]:  # 检查当前单元格是否是合并单元格的起始单元格rowspan = [m[2] - m[0] + 1 for m in merges if m[0] == row_idx and m[1] == col_idx][0]colspan = [m[3] - m[1] + 1 for m in merges if m[0] == row_idx and m[1] == col_idx][0]if style:html += f"<td style='{font_style} {border_style} {alignment_style}' rowspan={rowspan} colspan={colspan}>{cell}</td>"else:html += f"<td rowspan={rowspan} colspan={colspan}>{cell}</td>"skip_next_cell = colspan - 1    # 跳过合并的列else:if style:html += f"<td style='{font_style} {border_style} {alignment_style}' >{cell}</td>"else:html += f"<td>{cell}</td>"html += "</tr>\n"html += "</table>"html = "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Excel Table</title></head><body>" + html + "</body></html>"return htmldef main():current_dir = 'reer'excel_file_path = current_dir + 'log/2re0207.xlsx'  # 替换为你的Excel文件路径html_file_path = current_dir + 'log/output.html'screenshot_file_path = current_dir + 'log/table_screenshot.png'data, merges, cell_styles = read_excel(excel_file_path)html_table = generate_html_table(data, merges, cell_styles)with open(html_file_path, 'w', encoding='utf-8') as file:file.write(html_table)# 调用函数,替换以下参数url = html_file_path  # 网页URLoutput_file = screenshot_file_path  # 输出文件路径table_selector = 'table'  # 表格的CSS选择器,根据实际情况调整capture_table_screenshot(url, output_file, table_selector)if __name__ == "__main__":main()


http://www.ppmy.cn/server/166132.html

相关文章

TaskBuilder项目实战:创建项目

用TaskBuilder开发应用系统的第一步就是创建项目&#xff0c;项目可以是一个简单的功能模块&#xff0c;也可以是很多功能模块的集合&#xff0c;具体怎么划分看各位的实际需要&#xff0c;我们一般会将相互关联比较紧密的一组功能模块放到一个独立的项目内&#xff0c;以便打包…

基于javaweb的SpringBoot小区智慧园区管理系统(源码+文档+部署讲解)

&#x1f3ac; 秋野酱&#xff1a;《个人主页》 &#x1f525; 个人专栏:《Java专栏》《Python专栏》 ⛺️心若有所向往,何惧道阻且长 文章目录 运行环境开发工具适用功能说明 运行环境 Java≥8、MySQL≥5.7、Node.js≥14 开发工具 后端&#xff1a;eclipse/idea/myeclipse…

DeepFM:融合因子分解机与深度学习的CTR预测模型

引言 点击率&#xff08;Click-Through Rate, CTR&#xff09;预测是推荐系统和计算广告领域的核心任务。传统方法通常依赖人工特征工程或单一模型架构&#xff0c;难以同时捕捉低阶与高阶特征交互。为了克服这些限制&#xff0c;研究者们不断探索新的模型架构&#xff0c;以更…

基于ArcGIS的SWAT模型+CENTURY模型模拟流域生态系统水-碳-氮耦合过程研究

流域是一个相对独立的自然地理单元&#xff0c;它是以水系为纽带&#xff0c;将系统内各自然地理要素连结成一个不可分割的整体。碳和氮是陆地生态系统中最重要的两种化学元素&#xff0c;而在流域系统内&#xff0c;水-碳-氮是相互联动、不可分割的耦合体。随着流域内人类活动…

ansible自动化运维

ansible自动化运维 1、实现远程连接主机 2、批量配置&#xff0c;批量操作&#xff0c;ansible可以对主机进行组划分&#xff0c;也可以把名下所有的主机进行划分&#xff0c;进行批量的操作。 3、远程自动化运维&#xff08;脚本-------------playbook剧本&#xff09; an…

自定义飞书Webhook机器人api接口

自定义飞书Webhook机器人api接口 使用方法&#xff1a; 在网站目录新建一个名为api.php的文件&#xff0c;将以上代码粘贴进去即可 然后访问域名/api.php?title洛小柒 - QQ沐编程&content小柒祝大家新年快乐&#xff01;&urlwww.qqmu.com&type1 title是标题 con…

用 HTML、CSS 和 JavaScript 实现抽奖转盘效果

顺序抽奖 前言 这段代码实现了一个简单的抽奖转盘效果。页面上有一个九宫格布局的抽奖区域&#xff0c;周围八个格子分别放置了不同的奖品名称&#xff0c;中间是一个 “开始抽奖” 的按钮。点击按钮后&#xff0c;抽奖区域的格子会快速滚动&#xff0c;颜色不断变化&#xf…

基于ssm的药店管理系统

一、系统架构 前端&#xff1a;jsp | bootstrap | jquery | css | ajax 后端&#xff1a;spring| springmvc | mybatis 环境&#xff1a;jdk1.8 | mysql | maven | tomcat 二、代码及数据 三、功能介绍 01. 注册 02. 登录 03. 管理员-药品基础信息 04.…