JScript で Excel

Excel ファイルを 作成する

lesson006.js


var objExcel = WScript.CreateObject("Excel.Application");
objExcel.Visible = true;
objExcel.DisplayAlerts = false; //警告メッセージをOFF

//ブックを読み取り専用で開く
var bookIn = objExcel.Workbooks.Open(WScript.Arguments(0));

//ブックを書き込み用で開く
var bookOut = objExcel.Workbooks.Add;

//いったん、シートを1枚だけにする
for (var iSheet = bookOut.WorkSheets.Count; iSheet > 1; iSheet--)
{
bookOut.WorkSheets(iSheet).Delete;
}

for (var iSheet = 1; iSheet <= bookIn.WorkSheets.Count; iSheet++)
{
//必要なら、シートを追加する
if (iSheet > bookOut.WorkSheets.Count)
bookOut.Sheets.Add(null, bookOut.WorkSheets(iSheet - 1));

var sheetIn = bookIn.WorkSheets(iSheet);
var sheetOut = bookOut.WorkSheets(iSheet);

//シート名を変更する
if (sheetOut.Name != sheetIn.Name)
sheetOut.Name = sheetIn.Name;

//データをコピーする
for (var iRow = 1; iRow <= sheetIn.Cells.CurrentRegion.Rows.Count; iRow++)
{
for (var iCol = 1; iCol <= sheetIn.Cells.CurrentRegion.Columns.Count; iCol++)
{
sheetOut.Cells(iRow, iCol).Value = sheetIn.Cells(iRow, iCol).Value;
}
}
}

//ブックを保存する
bookOut.SaveAs(WScript.Arguments(1));

objExcel.Quit();
objExcel = null;

実行結果

C:\>cscript c:\study\jscript\chapter004\lesson006.js c:\study\Book1.xls c:\study
\Book2.xls //nologo