Skip to content

Instantly share code, notes, and snippets.

@jsmpros
Last active March 31, 2023 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsmpros/420b4ac68b4207d684036d3aebab1b8e to your computer and use it in GitHub Desktop.
Save jsmpros/420b4ac68b4207d684036d3aebab1b8e to your computer and use it in GitHub Desktop.
JavaScript that reads binary excel files using POI and inserts rows into a PeopleSoft table
// endsWith polyfill
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) ||
Math.floor(position) !== position ||
position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
// open a workbook, iterate over rows/cells, and then insert them into a
// staging table
var result = (function() {
// declare pointers to Java methods to make it easier to invoke the methods
// by name
var FileInputStream = Packages.java.io.FileInputStream;
var HSSFWorkbook = Packages.org.apache.poi.hssf.usermodel.HSSFWorkbook;
var Workbook = Packages.org.apache.poi.ss.usermodel.Workbook;
var XSSFWorkbook = Packages.org.apache.poi.xssf.usermodel.XSSFWorkbook;
// declare a PeopleCode function
var SQLExec = Packages.PeopleSoft.PeopleCode.Func.SQLExec;
// internal "helper" function that will identify inserted rows
var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
}
);
// open a binary Microsoft Excel file
var fis = new FileInputStream(fileName);
var workbook;
if(fileName.toLowerCase().endsWith("xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if(fileName.toLowerCase().endsWith("xls")) {
workbook = new HSSFWorkbook(fis);
}
var sheet = workbook.getSheetAt(0);
var rowIterator = sheet.iterator();
var roleName,
descr,
row;
// iterate over each row, inserting those rows into a staging table
while (rowIterator.hasNext()) {
row = rowIterator.next();
roleName = row.getCell(0).getStringCellValue();
descr = row.getCell(1).getStringCellValue();
// TODO: turn this into a stored SQL definition, not hard coded SQL
SQLExec("INSERT INTO PS_JSM_XLROLE_STG VALUES(:1, :2, :3, SYSTIMESTAMP)",
// notice that the SQLExec parameters are wrapped in an array
[guid, roleName, descr]
);
}
// return the unique identifier that can later be used to select the rows
// inserted by this process
return guid;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment