如何使用javascript将Excel工作簿保存到当前用户桌面

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

本文关键字:用户 桌面 保存 工作簿 何使用 javascript Excel      更新时间:2024-05-30

我通过以下方式从网页创建工作簿:

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

但对于objWorkbook.Worksheets(1).SaveAs("%USERPROFILE%''Desktop''xxx.xls");,它不会保存到桌面,并给出以下错误:

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.

来自@PA。答复我终于得到的答复

//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。

您假设javascript在字符串中扩展环境变量。不幸的是,事实并非如此。

您需要在代码中对其进行扩展。使用wscript.shell对象的Environment属性可以访问任何环境变量。

首先,访问wscript.shell对象。在WSH中,使用

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

或者在浏览器中使用

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

然后

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

或者您可以使用ExpandEnvironmentStrings方法来扩展字符串中的变量

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