2

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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")
);

2 Comments

var wshell = WScript.CreateObject("wscript.shell"); Give this error SCRIPT5009: 'WScript' is undefined
this is available in Windows Script Hosting. In browsers use ActiveXObject. I have edited the answer to reflect it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.