使用 python 打印 Excel 工作簿

Print Excel workbook using python

假设我有一个 excel 文件 excel_file.xlsx,我想使用 Python 将它发送到我的打印机,所以我使用:

import os
os.startfile('path/to/file','print')

我的问题是这只会打印 excel 工作簿的第一个 sheet,但我想要打印所有 sheet。有没有办法打印整个工作簿?

此外,我使用 Openpyxl 创建文件,但似乎没有任何选项可以 select 打印 sheet 的数量。

如有任何帮助,我们将不胜感激。

from xlrd import open_workbook
from openpyxl.reader.excel import load_workbook
import os
import shutil

path_to_workbook = "/Users/username/path/sheet.xlsx"
worksheets_folder = "/Users/username/path/worksheets/"
workbook = open_workbook(path_to_workbook)


def main():

    all_sheet_names = []
    for s in workbook.sheets():
        all_sheet_names.append(s.name)

    for sheet in workbook.sheets():

        if not os.path.exists("worksheets"):
            os.makedirs("worksheets")

        working_sheet = sheet.name

        path_to_new_workbook = worksheets_folder + '{}.xlsx'.format(sheet.name)

        shutil.copyfile(path_to_workbook, path_to_new_workbook)

        nwb = load_workbook(path_to_new_workbook)

        print "working_sheet = " + working_sheet

        for name in all_sheet_names:

            if name != working_sheet:
                nwb.remove_sheet(nwb.get_sheet_by_name(name))

        nwb.save(path_to_new_workbook)

    ws_files = get_file_names(worksheets_folder, ".xlsx")

    # Uncomment print command
    for f in xrange(0, len(ws_files)):
        path_to_file = worksheets_folder + ws_files[f]
        # os.startfile(path_to_file, 'print')
        print 'PRINT: ' + path_to_file

    # remove worksheets folder
    shutil.rmtree(worksheets_folder)


def get_file_names(folder, extension):
    names = []
    for file_name in os.listdir(folder):
        if file_name.endswith(extension):
            names.append(file_name)
    return names


if __name__ == '__main__':
    main()

可能不是最好的方法,但它应该有效。 作为一种解决方法,您可以创建单独的 .xlsx 文件,其中每个文件只有一个电子表格,然后使用 os.startfile(path_to_file, 'print')

打印它们

您可以在 open() 命令中嵌入 vBa,以使用本文中提到的 xlsxwriter 实用程序将 excel 文件打印到默认打印机: PBPYthon's Embed vBA in Excel

事实证明,问题出在 Microsoft Excel, os.startfile 只是将文件发送到用于打开这些文件类型的系统默认应用程序。我只需要将默认设置更改为另一个应用程序(在我的情况下是 WPS Office),问题就解决了。

看来您应该能够循环浏览并更改哪个页面处于活动状态。我尝试了这个,它确实打印了每个 sheet,但是无论出于何种原因,在第一次打印时它把两个 sheet 组合在一起,所以它给了我每个工作簿一个重复的页面。

wb = op.load_workbook(filepath)

for sheet in wb.sheetnames:
    sel_sheet = wb[sheet]


    # find the max row and max column in the sheet
    max_row = sel_sheet.max_row
    max_column = sel_sheet.max_column

    # identify the sheets that have some data in them
    if (max_row > 1) & (max_column > 1):

        # Creating new file for each sheet
        sheet_names = wb.sheetnames
        wb.active = sheet_names.index(sheet)

        wb.save(filepath)
        os.startfile(filepath, "print")

我遇到过这个问题(在 windows 上),使用 pywin32 模块和这个代码块解决了这个问题(在第 5 行中,您可以指定要打印的纸张。)

    import win32com.client
    o = win32com.client.Dispatch('Excel.Application')
    o.visible = True
    wb = o.Workbooks.Open('/Users/1/Desktop/Sample.xlsx')
    ws = wb.Worksheets([1 ,2 ,3])
    ws.printout()