Java Code Examples for org.apache.poi.hssf.usermodel.HSSFSheet#getRow()

The following examples show how to use org.apache.poi.hssf.usermodel.HSSFSheet#getRow() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: POIUtils.java    From ermaster-b with Apache License 2.0 6 votes vote down vote up
public static CellLocation findMatchCell(HSSFSheet sheet, String regexp) {
	for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet
			.getLastRowNum() + 1; rowNum++) {
		HSSFRow row = sheet.getRow(rowNum);
		if (row == null) {
			continue;
		}

		Integer colNum = findMatchColumn(row, regexp);

		if (colNum != null) {
			return new CellLocation(rowNum, colNum.shortValue());
		}
	}

	return null;
}
 
Example 2
Source File: Util.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param destination
 *            the sheet to create from the copy.
 * @param the
 *            sheet to copy.
 * @param copyStyle
 *            true copy the style.
 */
private static void copySheet(List<CellStyle> list, HSSFSheet source, XSSFSheet destination, boolean copyStyle) {
	int maxColumnNum = 0;
	List<CellStyle> styleMap = null;
	if (copyStyle) {
		styleMap = list;
	}

	for (int i = source.getFirstRowNum(); i <= source.getLastRowNum(); i++) {
		HSSFRow srcRow = source.getRow(i);
		XSSFRow destRow = destination.createRow(i);

		if (srcRow != null) {

			copyRow(source, destination, srcRow, destRow, styleMap);
			if (srcRow.getLastCellNum() > maxColumnNum) {
				maxColumnNum = srcRow.getLastCellNum();
			}
		}
	}
	destination.shiftRows(destination.getFirstRowNum(), destination.getLastRowNum(), 3);
	for (int i = 0; i <= maxColumnNum; i++) {
		destination.autoSizeColumn(i);
	}
}
 
Example 3
Source File: POIUtils.java    From ermasterr with Apache License 2.0 6 votes vote down vote up
public static CellLocation findMatchCell(final HSSFSheet sheet, final String regexp) {
    for (int rowNum = sheet.getFirstRowNum(); rowNum < sheet.getLastRowNum() + 1; rowNum++) {
        final HSSFRow row = sheet.getRow(rowNum);
        if (row == null) {
            continue;
        }

        final Integer colNum = findMatchColumn(row, regexp);

        if (colNum != null) {
            return new CellLocation(rowNum, colNum.shortValue());
        }
    }

    return null;
}
 
Example 4
Source File: Prd4434IT.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testExcelExport() throws Exception {
  final MasterReport report = DebugReportRunner.parseGoldenSampleReport( "Prd-3625.prpt" );

  final ByteArrayOutputStream bout = new ByteArrayOutputStream();
  ExcelReportUtil.createXLS( report, bout );

  final HSSFWorkbook wb = new HSSFWorkbook( new ByteArrayInputStream( bout.toByteArray() ) );
  final HSSFSheet sheetAt = wb.getSheetAt( 0 );
  final HSSFRow row = sheetAt.getRow( 0 );
  final HSSFCell cell0 = row.getCell( 0 );
  assertEquals( Cell.CELL_TYPE_NUMERIC, cell0.getCellType() );
  assertEquals( "yyyy-MM-dd", cell0.getCellStyle().getDataFormatString() );
  final HSSFCell cell1 = row.getCell( 1 );
  assertEquals( Cell.CELL_TYPE_NUMERIC, cell1.getCellType() );
  assertEquals( "#,###.00;(#,###.00)", cell1.getCellStyle().getDataFormatString() );
}
 
Example 5
Source File: StyleTest.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
@Test
public void poi() throws Exception {
    InputStream is = new FileInputStream("D:\\test\\styleTest.xls");
    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
    HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
    HSSFRow hssfRow = hssfSheet.getRow(0);
    System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
    DataFormatter formatter = new DataFormatter();
    System.out.println(hssfRow.getCell(0).getNumericCellValue());
    System.out.println(hssfRow.getCell(1).getNumericCellValue());
    System.out.println(hssfRow.getCell(2).getNumericCellValue());
    System.out.println(hssfRow.getCell(0).getCellStyle().getDataFormatString());
    System.out.println(hssfRow.getCell(1).getCellStyle().getDataFormatString());
    System.out.println(hssfRow.getCell(2).getCellStyle().getDataFormatString());

}
 
Example 6
Source File: ResidenceEventManagementService.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public List<ResidenceEventBean> process(final ResidenceMonth residenceMonth, MultipartFile file) throws IOException, InvalidSpreadSheetName {
    List<ResidenceEventBean> beans = new ArrayList<>();

    POIFSFileSystem fs = new POIFSFileSystem(file.getInputStream());
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);

    if (sheet == null) {
        throw new InvalidSpreadSheetName(file.getOriginalFilename(), getAllSpreadsheets(wb));
    }

    for (int i = 2; sheet.getRow(i) != null; i++) {
        HSSFRow row = sheet.getRow(i);

        String room = row.getCell(0).getStringCellValue();
        if (StringUtils.isEmpty(room)) {
            break;
        }

        String userName = getValueFromColumnMayBeNull(row, 1);
        String fiscalNumber = getValueFromColumnMayBeNull(row, 2);
        String name = getValueFromColumnMayBeNull(row, 3);
        Double roomValue = row.getCell(4).getNumericCellValue();

        beans.add(new ResidenceEventBean(residenceMonth, userName, fiscalNumber, name, roomValue, room));
    }
    return beans;
}
 
Example 7
Source File: ReportStudentsUTLCandidates.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void addHeaderCell(HSSFSheet sheet, String value, int columnNumber) {
    HSSFRow row = sheet.getRow(0);
    HSSFCell cell = row.createCell(columnNumber);

    cell.setCellValue(value);
    cell.setCellStyle(headerStyle);

    sheet.addMergedRegion(new CellRangeAddress(0, 1, columnNumber, columnNumber));
}
 
Example 8
Source File: PictureSheetGenerator.java    From ermaster-b with Apache License 2.0 5 votes vote down vote up
private float getRowHeightInPixels(HSSFSheet sheet, int i) {
	HSSFRow row = sheet.getRow(i);
	float height;
	if (row != null) {
		height = row.getHeight();
	} else {
		height = sheet.getDefaultRowHeight();
	}

	return height / 15F;
}
 
Example 9
Source File: InvestmentSummaryController.java    From primefaces-blueprints with The Unlicense 5 votes vote down vote up
public void postProcessXLS(Object document) {  
    HSSFWorkbook wb = (HSSFWorkbook) document;  
    HSSFSheet sheet = wb.getSheetAt(0);  
    HSSFRow header = sheet.getRow(0);  
      
    HSSFCellStyle cellStyle = wb.createCellStyle();    
    cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);  
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
      
    for(int i=0; i < header.getPhysicalNumberOfCells();i++) {  
        HSSFCell cell = header.getCell(i);  
          
        cell.setCellStyle(cellStyle);  
    }  
    
    Row row=sheet.createRow((short)sheet.getLastRowNum()+3);
    Cell cellDisclaimer = row.createCell(0);
    HSSFFont customFont= wb.createFont();
    customFont.setFontHeightInPoints((short)10);
    customFont.setFontName("Arial");
    customFont.setColor(IndexedColors.BLACK.getIndex());
    customFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    customFont.setItalic(true);
    
    cellDisclaimer.setCellValue("Disclaimer");
    HSSFCellStyle cellStyleDisclaimer = wb.createCellStyle();
    cellStyleDisclaimer.setFont(customFont);
    cellDisclaimer.setCellStyle(cellStyleDisclaimer);
    
    Row row1=sheet.createRow(sheet.getLastRowNum()+2);
    Cell cellDisclaimerContent1 = row1.createCell(0);
    cellDisclaimerContent1.setCellValue("The information contained in this website is for information purposes only, and does not constitute, nor is it intended to constitute, the provision of financial product advice.");
    
    Row row2=sheet.createRow(sheet.getLastRowNum()+1);
    Cell cellDisclaimerContent2 = row2.createCell(0);
    cellDisclaimerContent2.setCellValue("This website is intended to track the investor account summary information,investments and transaction in a partcular period of time. ");
    
}
 
Example 10
Source File: PhdReport.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void addHeaderCell(HSSFSheet sheet, String value, int columnNumber) {
    HSSFRow row = sheet.getRow(0);
    if (row == null) {
        row = sheet.createRow(0);
    }

    HSSFCell cell = row.createCell(columnNumber);

    cell.setCellValue(value);
    cell.setCellStyle(headerStyle);

    cell.setCellValue(value);

    sheet.addMergedRegion(new CellRangeAddress(0, 1, columnNumber, columnNumber));
}
 
Example 11
Source File: HSSFCellHelper.java    From yarg with Apache License 2.0 5 votes vote down vote up
public static HSSFCell getCellFromReference(HSSFSheet templateSheet, int colIndex, int rowIndex) {
    HSSFRow row = templateSheet.getRow(rowIndex);
    row = row == null ? templateSheet.createRow(rowIndex) : row;
    HSSFCell cell = row.getCell(colIndex);
    cell = cell == null ? row.createCell(colIndex) : cell;
    return cell;
}
 
Example 12
Source File: AccountSummaryController.java    From primefaces-blueprints with The Unlicense 5 votes vote down vote up
public void postProcessXLS(Object document) {  
    HSSFWorkbook wb = (HSSFWorkbook) document;  
    HSSFSheet sheet = wb.getSheetAt(0);  
    HSSFRow header = sheet.getRow(0);  
    HSSFCellStyle cellStyle = wb.createCellStyle();    
    cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);  
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
      
    for(int i=0; i < header.getPhysicalNumberOfCells();i++) {  
        HSSFCell cell = header.getCell(i);  
          
        cell.setCellStyle(cellStyle);  
    }  
    Row row=sheet.createRow((short)sheet.getLastRowNum()+3);
    Cell cellDisclaimer = row.createCell(0);
    HSSFFont customFont= wb.createFont();
    customFont.setFontHeightInPoints((short)10);
    customFont.setFontName("Arial");
    customFont.setColor(IndexedColors.BLACK.getIndex());
    customFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    customFont.setItalic(true);
    
    cellDisclaimer.setCellValue("Disclaimer");
    HSSFCellStyle cellStyleDisclaimer = wb.createCellStyle();
    cellStyleDisclaimer.setFont(customFont);
    cellDisclaimer.setCellStyle(cellStyleDisclaimer);
    
    Row row1=sheet.createRow(sheet.getLastRowNum()+2);
    Cell cellDisclaimerContent1 = row1.createCell(0);
    cellDisclaimerContent1.setCellValue("The information contained in this website is for information purposes only, and does not constitute, nor is it intended to constitute, the provision of financial product advice.");	    
    Row row2=sheet.createRow(sheet.getLastRowNum()+1);
    Cell cellDisclaimerContent2 = row2.createCell(0);
    cellDisclaimerContent2.setCellValue("This website is intended to track the investor account summary information,investments and transaction in a partcular period of time. ");
    
}
 
Example 13
Source File: ExcelUtil.java    From phone with Apache License 2.0 5 votes vote down vote up
/**
 * 读取excel到JsonArray
 * @param sheet
 * @param map 列对应的column
 * @param rowNumber
 * @param array
 * @return 当前的rowNumber
 */
   private static int readSheetBody(HSSFSheet sheet, Map<Integer, String> map, int rowNumber, JSONArray array) {
	if (logger.isDebugEnabled()) {
		logger.debug("readSheetBody(HSSFSheet, Map<Integer,String>, int, JSONArray) - start"); //$NON-NLS-1$
	}

   	if(sheet!=null){
		int end = sheet.getLastRowNum();//获取最后一行
		for (; rowNumber<=end;rowNumber++) {
			HSSFRow row = sheet.getRow(rowNumber);
			if (row!=null) {
				JSONObject jsonObject = new JSONObject();
				Iterator<Cell> iterator = row.cellIterator();
				while (iterator.hasNext()) {
					Cell cell = iterator.next();
					if (cell!=null) {
						int cellIndex = cell.getColumnIndex();
						String key = map.get(cellIndex);
						String cellValue = getStringValue(cell);
						if (key!=null&&cellValue!=null&&!cellValue.equals("null")) {
							readSheetCell(jsonObject,key,cellValue);
						}
						
					}
				}
				array.add(jsonObject);
			}
		}
	}

	if (logger.isDebugEnabled()) {
		logger.debug("readSheetBody(HSSFSheet, Map<Integer,String>, int, JSONArray) - end"); //$NON-NLS-1$
	}
	return rowNumber;
}
 
Example 14
Source File: HSSFExcelParser.java    From ureport with Apache License 2.0 5 votes vote down vote up
private int buildMaxColumn(HSSFSheet sheet){
	int rowCount=sheet.getPhysicalNumberOfRows();
	int maxColumnCount=0;
	for(int i=0;i<rowCount;i++){
		HSSFRow row=sheet.getRow(i);
		if(row==null){
			continue;
		}
		int columnCount=row.getPhysicalNumberOfCells();
		if(columnCount>maxColumnCount){
			maxColumnCount=columnCount;
		}
	}
	return maxColumnCount;
}
 
Example 15
Source File: ToolImport.java    From android-lang-tool with Apache License 2.0 5 votes vote down vote up
private void parse(HSSFSheet sheet) throws IOException, TransformerException {
    Row row = sheet.getRow(0);
    Iterator<Cell> cells = row.cellIterator();
    cells.next();// ignore key
    int i = 1;
    while (cells.hasNext()) {
        String lang = cells.next().toString();
        if (mMapping != null && mMapping.containsKey(lang)) {
            lang = mMapping.get(lang);
        }
        generateLang(sheet, lang, i);
        i++;
    }
}
 
Example 16
Source File: ColumnSheetGenerator.java    From ermasterr with Apache License 2.0 5 votes vote down vote up
public void setAllColumnsData(final ProgressMonitor monitor, final HSSFWorkbook workbook, final HSSFSheet sheet, final ERDiagram diagram) throws InterruptedException {
    clear();

    final CellLocation cellLocation = POIUtils.findCell(sheet, FIND_KEYWORDS_OF_COLUMN);

    if (cellLocation != null) {
        int rowNum = cellLocation.r;
        final HSSFRow templateRow = sheet.getRow(rowNum);

        if (columnTemplate == null) {
            columnTemplate = loadColumnTemplate(workbook, sheet, cellLocation);
        }

        int order = 1;

        for (final ERTable table : diagram.getDiagramContents().getContents().getTableSet()) {

            if (diagram.getCurrentCategory() != null && !diagram.getCurrentCategory().contains(table)) {
                continue;
            }

            monitor.subTaskWithCounter(sheet.getSheetName() + " - " + table.getName());

            for (final NormalColumn normalColumn : table.getExpandedColumns()) {

                final HSSFRow row = POIUtils.insertRow(sheet, rowNum++);
                setColumnData(keywordsValueMap, columnTemplate, row, normalColumn, table, order);
                order++;
            }

            monitor.worked(1);
        }

        setCellStyle(columnTemplate, sheet, cellLocation.r, rowNum - cellLocation.r, templateRow.getFirstCellNum());
    }
}
 
Example 17
Source File: OfficeConverter.java    From BBSSDK-for-Android with Apache License 2.0 4 votes vote down vote up
private void xlsToHtml() throws Throwable {
	FileOutputStream output = new FileOutputStream(new File(htmlPath));
	StringBuffer htmlHeaderSB = new StringBuffer();
	htmlHeaderSB.append("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' "
			+ "xmlns='http://www.w3.org/TR/REC-html40'>");
	htmlHeaderSB.append("<head><meta http-equiv=Content-Type content='text/html; charset=utf-8'><meta name=ProgId content=Excel.Sheet>"
			+ "</head><body>");
	output.write(htmlHeaderSB.toString().getBytes());
	HSSFSheet sheet;
	HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filePath)); // 获整个Excel
	for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
		if (workbook.getSheetAt(sheetIndex) != null) {
			sheet = workbook.getSheetAt(sheetIndex);// 获得不为空的这个sheet
			if (sheet != null) {
				int firstRowNum = sheet.getFirstRowNum(); // 第一行
				int lastRowNum = sheet.getLastRowNum(); // 最后一行
				// 构造Table
				output.write(("<table width=\"100%\" style=\"border:1px solid #000;border-width:1px 0 0 1px;margin:2px 0 2px 0;"
						+ "border-collapse:collapse;\">").getBytes());
				for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
					if (sheet.getRow(rowNum) != null) {// 如果行不为空,
						HSSFRow row = sheet.getRow(rowNum);
						short firstCellNum = row.getFirstCellNum(); // 该行的第一个单元格
						short lastCellNum = row.getLastCellNum(); // 该行的最后一个单元格
						int height = (int) (row.getHeight() / 15.625); // 行的高度
						output.write(("<tr height=\"" + height + "\" style=\"border:1px solid #000;border-width:0 1px 1px 0;"
								+ "margin:2px 0 2px 0;\">").getBytes());
						for (short cellNum = firstCellNum; cellNum <= lastCellNum; cellNum++) { // 循环该行的每一个单元格
							HSSFCell cell = row.getCell(cellNum);
							if (cell != null) {
								if (cell.getCellType() != HSSFCell.CELL_TYPE_BLANK) {
									StringBuffer tdStyle = new StringBuffer("<td style=\"border:1px solid #000; border-width:0 1px 1px 0;"
											+ "margin:2px 0 2px 0; ");
									HSSFCellStyle cellStyle = cell.getCellStyle();
									HSSFPalette palette = workbook.getCustomPalette(); // 类HSSFPalette用于求颜色的国际标准形式
									HSSFColor hColor = palette.getColor(cellStyle.getFillForegroundColor());
									HSSFColor hColor2 = palette.getColor(cellStyle.getFont(workbook).getColor());
									String bgColor = convertToStardColor(hColor);// 背景颜色
									short boldWeight = cellStyle.getFont(workbook).getBoldweight(); // 字体粗细
									short fontHeight = (short) (cellStyle.getFont(workbook).getFontHeight() / 2); // 字体大小
									String fontColor = convertToStardColor(hColor2); // 字体颜色
									if (bgColor != null && !"".equals(bgColor.trim())) {
										tdStyle.append(" background-color:");
										tdStyle.append(bgColor);
										tdStyle.append("; ");
									}
									if (fontColor != null && !"".equals(fontColor.trim())) {
										tdStyle.append(" color:");
										tdStyle.append(fontColor);
										tdStyle.append("; ");
									}
									tdStyle.append(" font-weight:");
									tdStyle.append(boldWeight);
									tdStyle.append("; ");
									tdStyle.append(" font-size: ");
									tdStyle.append(fontHeight);
									tdStyle.append("%;");
									output.write((tdStyle + "\"").getBytes());

									int width = (int) (sheet.getColumnWidth(cellNum) / 35.7); //
									int cellRegionCol = getMergerCellRegionCol(sheet, rowNum, cellNum); // 合并的列(solspan)
									int cellRegionRow = getMergerCellRegionRow(sheet, rowNum, cellNum);// 合并的行(rowspan)
									String align = convertAlignToHtml(cellStyle.getAlignment()); //
									String vAlign = convertVerticalAlignToHtml(cellStyle.getVerticalAlignment());

									output.write((" align=\"" + align + "\" valign=\"" + vAlign + "\" width=\"" + width + "\" ").getBytes());
									output.write((" colspan=\"" + cellRegionCol + "\" rowspan=\"" + cellRegionRow + "\"").getBytes());
									output.write((">" + getCellValue(cell) + "</td>").getBytes());
								}
							}
						}
						output.write("</tr>".getBytes());
					}
				}
				output.write(("</table>").getBytes());
			}
		}
	}
	output.write(("</body></html>").getBytes());
	output.close();
}
 
Example 18
Source File: ImportService.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
   public List parseRolesSpreadsheet(MultipartFile fileItem, String sessionId) throws IOException {
results = new ArrayList<>();
HSSFSheet sheet = getSheet(fileItem);
int startRow = sheet.getFirstRowNum();
int endRow = sheet.getLastRowNum();

ImportService.log.debug("Parsing spreadsheet rows " + startRow + " through " + endRow);

setupImportStatus(sessionId, endRow - startRow);
UserDTO userDTO = (UserDTO) SessionManager.getSession(sessionId).getAttribute(AttributeNames.USER);

HSSFRow row;
List<String> roles;
int successful = 0;
for (int i = startRow + 1; i < (endRow + 1); i++) {
    emptyRow = true;
    hasError = false;
    rowResult = new ArrayList<>();
    row = sheet.getRow(i);

    String login = parseStringCell(row.getCell(ImportService.LOGIN));
    String orgId = parseStringCell(row.getCell(ImportService.ORGANISATION));
    roles = parseRolesCell(row.getCell(ImportService.ROLES));

    if (emptyRow) {
	ImportService.log.debug("Row " + i + " is empty.");
	break;
    }
    if (hasError) {
	ImportService.log.debug("Row " + i + " has an error which has been sent to the browser.");
	results.add(rowResult);
	writeErrorsAuditLog(i + 1, rowResult, userDTO);
	updateImportStatus(sessionId, results.size());
	continue;
    } else {
	try {
	    saveUserRoles(isSysadmin(sessionId), login, orgId, roles, row);
	    successful++;
	} catch (Exception e) {
	    ImportService.log.error("Unable to assign roles to user: " + login, e);
	    rowResult.add(messageService.getMessage("error.fail.add"));
	}
	if (rowResult.size() > 0) {
	    if (ImportService.log.isDebugEnabled()) {
		ImportService.log.debug("Row " + i + " has " + rowResult.size() + " messages.");
	    }
	    writeErrorsAuditLog(i + 1, rowResult, userDTO);
	}
	results.add(rowResult);
	updateImportStatus(sessionId, results.size());
    }
}
ImportService.log.debug("Found " + results.size() + " users in spreadsheet.");
writeSuccessAuditLog(successful, userDTO, "audit.successful.role.import");
return results;
   }
 
Example 19
Source File: OutcomeService.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
   @SuppressWarnings("unchecked")
   public int importScales(MultipartFile fileItem) throws IOException {
int counter = 0;
POIFSFileSystem fs = new POIFSFileSystem(fileItem.getInputStream());
try (HSSFWorkbook wb = new HSSFWorkbook(fs)) {
    HSSFSheet sheet = wb.getSheetAt(0);
    int startRow = sheet.getFirstRowNum();
    int endRow = sheet.getLastRowNum();
    User user = null;

    // make import work with files with header ("exported on") or without (pure data)
    HSSFRow row = sheet.getRow(startRow);
    HSSFCell cell = row.getCell(0);
    String header = cell.getStringCellValue();
    startRow += "name".equalsIgnoreCase(header) ? 1 : 5;

    for (int i = startRow; i < (endRow + 1); i++) {
	row = sheet.getRow(i);
	cell = row.getCell(1);
	String code = cell.getStringCellValue();
	List<OutcomeScale> foundScales = outcomeDAO.findByProperty(OutcomeScale.class, "code", code);
	if (!foundScales.isEmpty()) {
	    if (log.isDebugEnabled()) {
		log.debug("Skipping an outcome scale with existing code: " + code);
	    }
	    continue;
	}
	cell = row.getCell(0);
	String name = cell.getStringCellValue();
	cell = row.getCell(2);
	String description = cell == null ? null : cell.getStringCellValue();
	cell = row.getCell(3);
	String itemsString = cell.getStringCellValue();

	OutcomeScale scale = new OutcomeScale();
	scale.setName(name);
	scale.setCode(code);
	scale.setDescription(description);
	if (user == null) {
	    UserDTO userDTO = OutcomeService.getUserDTO();
	    user = (User) outcomeDAO.find(User.class, userDTO.getUserID());
	}
	scale.setCreateBy(user);
	scale.setCreateDateTime(new Date());
	outcomeDAO.insert(scale);

	List<String> items = OutcomeScale.parseItems(itemsString);
	int value = 0;
	for (String itemString : items) {
	    OutcomeScaleItem item = new OutcomeScaleItem();
	    item.setName(itemString);
	    item.setValue(value++);
	    item.setScale(scale);
	    outcomeDAO.insert(item);
	}

	counter++;
    }
}
return counter;
   }
 
Example 20
Source File: OutcomeService.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
   @SuppressWarnings("unchecked")
   public int importOutcomes(MultipartFile fileItem) throws IOException {
int counter = 0;
POIFSFileSystem fs = new POIFSFileSystem(fileItem.getInputStream());
try (HSSFWorkbook wb = new HSSFWorkbook(fs)) {
    HSSFSheet sheet = wb.getSheetAt(0);
    int startRow = sheet.getFirstRowNum();
    int endRow = sheet.getLastRowNum();
    User user = null;

    // make import work with files with header ("exported on") or without (pure data)
    HSSFRow row = sheet.getRow(startRow);
    HSSFCell cell = row.getCell(0);
    String header = cell.getStringCellValue();
    startRow += "name".equalsIgnoreCase(header) ? 1 : 5;

    for (int i = startRow; i < (endRow + 1); i++) {
	row = sheet.getRow(i);
	cell = row.getCell(1);
	String code = cell.getStringCellValue();
	List<Outcome> foundOutcomes = outcomeDAO.findByProperty(Outcome.class, "code", code);
	if (!foundOutcomes.isEmpty()) {
	    if (log.isDebugEnabled()) {
		log.debug("Skipping an outcome with existing code: " + code);
	    }
	    continue;
	}
	cell = row.getCell(3);
	String scaleCode = cell.getStringCellValue();
	List<OutcomeScale> foundScales = outcomeDAO.findByProperty(OutcomeScale.class, "code", scaleCode);
	OutcomeScale scale = foundScales.isEmpty() ? null : foundScales.get(0);
	if (scale == null) {
	    if (log.isDebugEnabled()) {
		log.debug("Skipping an outcome with missing scale with code: " + scaleCode);
	    }
	    continue;
	}
	cell = row.getCell(0);
	String name = cell.getStringCellValue();
	cell = row.getCell(2);
	String description = cell == null ? null : cell.getStringCellValue();

	Outcome outcome = new Outcome();
	outcome.setName(name);
	outcome.setCode(code);
	outcome.setDescription(description);
	outcome.setScale(scale);
	if (user == null) {
	    UserDTO userDTO = OutcomeService.getUserDTO();
	    user = (User) outcomeDAO.find(User.class, userDTO.getUserID());
	}
	outcome.setCreateBy(user);
	outcome.setCreateDateTime(new Date());
	outcomeDAO.insert(outcome);

	counter++;
    }
}
return counter;
   }