Created
January 24, 2011 19:43
-
-
Save tricknotes/793810 to your computer and use it in GitHub Desktop.
Excelファイルの読み書き用ユーティリティ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Windows上でExcelを操作するためのシンプルなモジュールです。 | |
* ファイルのオープン・クローズを隠蔽しています。 | |
*/ | |
var excel = (function() { | |
var exports = {}; | |
// Excel操作 | |
var Operator = function(core) { | |
this.getCore = function() { | |
return core; | |
} | |
} | |
// API private | |
var operateWorkbook = function(workbook, fn) { | |
try { | |
fn(workbook); | |
} finally { | |
if (workbook) workbook.Close(); | |
} | |
} | |
// 簡易APIを提供 | |
var moduleOperator = function(name) { | |
exports[name] = function() { | |
var args = arguments; | |
operate(function(operator) { | |
operator[name].apply(operator, [].slice.apply(args)); | |
}); | |
} | |
} | |
// ファイル作成 | |
Operator.prototype.createFile = function(filename, fn) { | |
operateWorkbook(this.getCore().Workbooks.Add(), function(workbook){ | |
fn(workbook); | |
workbook.SaveAs(filename); | |
}); | |
} | |
moduleOperator("createFile"); | |
// ファイル更新 | |
Operator.prototype.updateFile = function(filename, fn) { | |
operateWorkbook(this.getCore().Workbooks.Open(filename), function(workbook){ | |
fn(workbook); | |
workbook.SaveAs(filename); | |
}); | |
} | |
moduleOperator("updateFile"); | |
// ファイル移動(コピーして編集) | |
Operator.prototype.copyFile = function(originalFilename, newFilename, fn) { | |
operateWorkbook(this.getCore().Workbooks.Open(originalFilename), function(workbook){ | |
fn && fn(workbook); // fn なしも許容する | |
workbook.SaveAs(newFilename); | |
}); | |
} | |
moduleOperator("copyFile"); | |
// ファイルを開く | |
Operator.prototype.openFile = function(filename, fn) { | |
operateWorkbook(this.getCore().Workbooks.Open(filename), function(workbook){ | |
fn(workbook); | |
}); | |
} | |
moduleOperator("openFile"); | |
// Excel操作 | |
var operate = exports.operate = function(fn) { | |
var core = new ActiveXObject("Excel.Application"); | |
core.Visible = false; | |
core.DisplayAlerts = false; | |
try { | |
fn(new Operator(core)); | |
} finally { | |
core.Quit(); | |
} | |
}; | |
return exports; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[Usage]
ファイルを新規に作成
既存のExcelファイルを更新
既存のExcelファイルをコピーして更新
Excelファイルを読み込む
複数のファイル操作を行う場合はoperateメソッドを利用するとCPUにやさしいです