JavaScript Excel.Application ActiveX cell.Value returns value of "date" type with no toString() in its prototype

StackOverflow https://stackoverflow.com/questions/21335200

  •  02-10-2022
  •  | 
  •  

質問

I'm facing an issue I have not seen before when working with Microsoft version of javascript.

I'm processing Excel documents through jscript ActiveX "Excel.Application" object. I'm running my script directly on my computer (this is not web application but a scripting tool).

I have this bit of code that works fine for most values I obtain from document:

var excel_application_object = new ActiveXObject("Excel.Application");
(...)
var excel_workbook_object = excel_application_object.Workbooks.Open("c:\\excel.xls");
(...)
var worksheet_object = excel_workbook_object.Sheets(1);
(...)
for ( var icnt = 1 ; icnt <= worksheet_object.Cells.SpecialCells(11).Row ; icnt ++ )
{
    WScript.Echo(typeof worksheet_object.Cells(kcnt, lcnt).Value);
    WScript.Echo(worksheet_object.Cells(kcnt, lcnt).Value.toString());
}

It seems that for some cells I'm getting an error when calling 'toString()'. Those cells type is quite strange:

typeof worksheet_object.Cells(kcnt, lcnt).Value == "date"

This can't be JavaScript Date object as

typeof (new Date()) == "object"

Did anyone came across this issue before? I need to parse value to String so I can do string operations later on.

Many thanks!

役に立ちましたか?

解決

You need to keep in mind, that you're handling values returned from an ActiveXObject. ActiveXs are not written with JavaScript (often used languaes are for example C, C++ or #C), hence they have not prototype, and are not implementing any ECMA-Script standards. The type of the returned value may vary, also the return value may be a type of not known in JS.

In your case it looks like you'd get a value from a cell containing an Excel Date object. Unlike JS, Excel has also native Date datatype, which JS's typeof operator seems to be able to read.

To get a string from an ActiveX property, you can do

var str = new String(ActiveX.property);

This is not bullet proof, but it has worked for me everywhere I've used it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top