There are some situations where we need to import data from the CSV or the XLS file. It's quite easy to deal with a CSV file, as this is a plain text file. But what about the XLS files. Servoy has the inbuilt mechanism to import from XLS file. But this is limited to smart client only.
To fix this issue, we come across some Java code which converts the XLS file to CSV. Then the same code which works for importing CSV data works well for this. This Java code uses Apache POI library. Below is the method which does the conversion. The eval
statements are to avoid the Servoy warning markers.
function convertXlsToCsv(file) {
var is = new java.io.ByteArrayInputStream(file.getBytes());
var workbook = eval("new org.apache.poi.hssf.usermodel.HSSFWorkbook(is)");
var sheet = eval("workbook.getSheetAt(0)");
var cell;
var data = '';
var rowStart = eval("sheet.getFirstRowNum()");
var rowEnd = eval("sheet.getLastRowNum()");
for (var rowNum = rowStart; rowNum <= rowEnd; rowNum++) {
var r = eval("sheet.getRow(rowNum)");
var lastColumn = eval("r.getLastCellNum()");
for (var cn = 0; cn < lastColumn; cn++) { if (cn > 0) {
data += (",");
}
cell = eval("r.getCell(cn, org.apache.poi.ss.usermodel.Row.RETURN_BLANK_AS_NULL)");
if (cell == null) {
data += ('""');
} else {
switch (eval("cell.getCellType()")) {
case eval("org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN"):
data += ("\"" + cell + "\"");
break;
case eval("org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC"):
if (eval("org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)"))
{
var dateFormat = eval("new java.text.SimpleDateFormat(dateTimeFormat)");
var strCellValue = eval("dateFormat.format(cell.getDateCellValue())");
data += ("\"" + strCellValue + "\"");
}
else {
data += ("\"" + eval("cell.getNumericCellValue()") + "\"");
}
break;
case eval("org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING"):
var str = eval("cell.getStringCellValue()");
var temp = str.toString();
temp = temp.split('"').join('\"\"');
utils.stringReplace(str.toString(), '"', '\"\"');
data += ("\"" + temp + "\"");
break;
case eval("org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BLANK"):
data += ("\"\"");
break;
default:
data += (cell);
}
}
}
data += ('\n');
}
return data;
}