MAXZZXAM
MAXZZXAM

Reputation: 137

How to save Excel workbook to current user desktop by using javascript?

I create workbook from web page by:

var thisTable = document.getElementById("mytable3").innerHTML;
       window.clipboardData.setData("Text", thisTable);
       var objExcel = new ActiveXObject ("Excel.Application");
       objExcel.visible = true;
       var objWorkbook = objExcel.Workbooks.Add();
       var objWorksheet = objWorkbook.Worksheets(1);
       objWorkbook.Worksheets(1).Activate;
       objWorksheet.name = "test";
       objWorksheet.Paste;
       objWorksheet.columns.autofit;
       window.clipboardData.setData("Text","");
       objWorkbook.Worksheets(1).SaveAs("%USERPROFILE%\\Desktop\\xxx.xls");

But for objWorkbook.Worksheets(1).SaveAs("%USERPROFILE%\\Desktop\\xxx.xls"); — it doesn't save to desktop and gives this error:

SCRIPT1004: Microsoft Excel cannot access the file 'C:\Users\user\Documents\%USERPROFILE%\Desktop\B612F000'. There are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.

Upvotes: 2

Views: 4543

Answers (2)

PA.
PA.

Reputation: 29339

You assume that javascript expands environment variables inside an string. Unfortunately for you, it does not.

you'll need to expand it in your code. Use the Environment property of the wscript.shell object to access any environment variable.

first, access the wscript.shell object. In WSH, use

var wshell = WScript.CreateObject("wscript.shell");

or in the browser use

var wshell = new ActiveXObject("WScript.Shell");

and then

var userProfile = wshell.Environment("USERPROFILE");

or you can expand the variable inside your string by using ExpandEnvironmentStrings method

objWorkbook.Worksheets(1).SaveAs(
  wshell.ExpandEnvironmentStrings("%USERPROFILE%\\Desktop\\xxx.xls")
);

Upvotes: 1

MAXZZXAM
MAXZZXAM

Reputation: 137

From @PA. Answer I finally got an answer by

//For Expand environment
  var wshShell = new ActiveXObject("WScript.Shell");
  var userProfile = wshShell.ExpandEnvironmentStrings("%USERPROFILE%\\Desktop\\test.xls");

  //For Save
  objWorkbook.Worksheets(1).SaveAs(userProfile);

Thak You @PA.

Upvotes: 1

Related Questions