Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print excel by command line?

I need to print without openning Microsoft Excel. For simple way, we can Right-Click on the excel file. Windows will display Context menu for choosing Print option from the context menu.

On other way, I we can open excel by command line. like these

   "excel c:\Users\loginid\Documents\data.xlsx"

But what possible if I need to print by command line. What command line for printing?

like image 389
Fame th Avatar asked Mar 13 '26 06:03

Fame th


2 Answers

PowerShell will do this easily. You can literally invoke the "Print" verb - doing exactly what Kyoujin recommended, from the command line. I'm running Win 10 1809, but I believe this is available all the way back to PowerShell 1.0:

powershell -command "start-process -filepath .\printermaintenancesheet.xlsx -verb print"

In this case, I'm launching a file in the current directory. If you need a full path, put it in single quotes (since you're using double quotes for the batch call to PowerShell):

powershell -command "start-process -filepath 'c:\users\fred\documents\sheetToPrint.xlsx' -verb print"

As indicated by Kyoujin, this will open Excel, load the file, print it, and close. You might want to make sure you set the print area in advance.

like image 138
user193479 Avatar answered Mar 15 '26 13:03

user193479


I found @user193479 answer didn't close excel consistently and was slow/opened the UI etc etc and I am comfortable with VBA so VBS is easy. I created a VBS script which takes the file as an argument and optionally a sheet name. I purposefully omitted "copies" and/or "printer" specification as I can handle that outside VBS via PrintUI and just repeating the call to the script. I already have methods for doing this to print PDF/Word etc and didn't want to add more arguments.

print_excel.vbs:

Dim XLApp
Dim XLWkbk
Dim ObjArgs
Dim strFileName
Dim strWorkSheetName

Set ObjArgs = wscript.arguments
Set XLApp= CreateObject("Excel.Application")
XLApp.Visible = False
Set XLWkbk = XLApp.Workbooks.Open(objargs(0))
If objArgs.count > 1 Then
 Set ws = XLWkbk.Sheets(objargs(1))
ELSE
 Set ws = XLWkbk.Worksheets(1)
End If
ws.PrintOut
XLWkbk.Close False
XLApp.Quit

Set XLWkbk = Nothing
Set XLApp = Nothing
Set ObjArgs = Nothing

Test:

wscript "C:\tmp\print_excel.vbs" "C:\tmp\Book1.xlsx" "Sheet2"
::wscript "C:\tmp\print_excel.vbs" "C:\tmp\Book1.xlsx"

https://www.freesoftwareservers.com/display/FREES/Print+Excel+Via+Command+Line+-+VBA+VBScript+-+Excel.exe+Switches

Also.... Word and PowerPoint have "print" switches to their respective executable... What the heck Microsoft....

like image 35
FreeSoftwareServers Avatar answered Mar 15 '26 13:03

FreeSoftwareServers