You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python 3.9打印电子表格数据如何调用打印预览功能

Python 3.9 调出打印预览界面解决方案

os.startfile('test.txt', 'print')调用的是系统默认的直接打印动作,不会触发打印预览,可根据你的使用场景选择以下方案:

方案1:Windows平台原生方案(无额外依赖)

Windows系统的Shell动词内置printpreview动作,可直接调用对应格式默认打开程序的原生打印预览界面,支持xlsx、xls、csv、txt等所有系统支持打印的文件格式:

import os

# 替换为你的电子表格文件路径
file_path = "test.xlsx"
os.startfile(file_path, "printpreview")

如果需要先筛选电子表格的部分数据再预览,可先处理数据生成临时文件再调用预览:

import pandas as pd
import os
import tempfile

# 读取原电子表格
df = pd.read_excel("你的原表格.xlsx")
# 自定义筛选规则,示例为取指定列、前20行数据
filtered_df = df.loc[:19, ["列名1", "列名2", "列名3"]]

# 生成临时存储的Excel文件
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as tmp_file:
    tmp_path = tmp_file.name
filtered_df.to_excel(tmp_path, index=False)

# 调出打印预览
os.startfile(tmp_path, "printpreview")

注意:该方案仅适配Windows平台,需提前安装对应电子表格的打开程序(如Excel、WPS等)并设置为默认打开程序

方案2:跨平台通用方案(适配Win/Mac/Linux)

如果需要跨平台运行,可通过PyQt5的打印组件自定义实现打印预览能力,可自主控制预览界面和打印内容样式:

  1. 先安装依赖:
pip install pyqt5 pandas openpyxl
  1. 示例代码:
import sys
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView, QPrintPreviewDialog
from PyQt5.QtPrintSupport import QPrinter
from PyQt5.QtGui import QStandardItemModel, QStandardItem

class CustomPrintPreview(QMainWindow):
    def __init__(self, filtered_data):
        super().__init__()
        # 加载筛选后的表格数据
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(filtered_data.columns.tolist())
        for row_data in filtered_data.values.tolist():
            item_list = [QStandardItem(str(cell)) for cell in row_data]
            self.model.appendRow(item_list)
        
        # 启动打印预览对话框
        self.printer = QPrinter(QPrinter.HighResolution)
        preview_dialog = QPrintPreviewDialog(self.printer, self)
        preview_dialog.paintRequested.connect(self.render_print_content)
        preview_dialog.exec_()

    def render_print_content(self, printer):
        table_view = QTableView()
        table_view.setModel(self.model)
        # 将表格内容渲染到打印设备
        table_view.render(printer)

if __name__ == "__main__":
    # 读取并筛选电子表格数据
    raw_df = pd.read_excel("原表格.xlsx")
    # 自定义筛选逻辑
    target_df = raw_df[raw_df["销售区域"] == "华东"]
    
    app = QApplication(sys.argv)
    preview_window = CustomPrintPreview(target_df)
    sys.exit(app.exec_())

内容的提问来源于stack exchange,提问作者mati_tylec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:27:03