python打印excel,使用python打印Excel工作簿

Suppose I have an excel file excel_file.xlsx and i want to send it to my printer using Python so I use:

import os

os.startfile('path_to_file','print')

My problem is that this only prints the first sheet of the excel workbook but i want all the sheets printed. Is there any way to print the entire workbook?

Also, I used Openpyxl to create the file, but it doesn't seem to have any option to select the number of sheets for printing.

Any help would be greatly appreciated.

EDIT-----

So far, it seems the only answer i could find was to create a temporary workbook for each sheet in excel_file.xlsx and print them one by one. But it isn't very efficient. I will keep searching and update when i find a better solution.

EDIT 2----

Turns out, the problem was with Microsoft Excel,

os.startfile just sends the file to the system's default app used to open those file types. I just had to change the default to another app(WPS Office in my case) and the problem was solved.

解决方案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()

probably not the best approach, but it should work.

As a workaround you can create separate .xlsx files where each has only one spreadsheet and then print them with os.startfile(path_to_file, 'print')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值