List of usage examples for org.apache.poi.hssf.usermodel HSSFWorkbook write
private void write(POIFSFileSystem fs) throws IOException
From source file:com.dexter.fuelcard.mbean.UserMBean.java
public void loadCards() { FacesContext curContext = FacesContextImpl.getCurrentInstance(); if (getUploadItem() != null) { try {/* w w w . j a v a 2 s. c om*/ HSSFWorkbook workbook = new HSSFWorkbook(getUploadItem().getInputstream()); int sheetCount = workbook.getNumberOfSheets(); if (sheetCount >= 1) { String password = getRandomDigitPassword(); HSSFSheet sheet = workbook.getSheetAt(0); // first sheet should be the main sheet sheet.protectSheet(password); ByteArrayOutputStream byout = new ByteArrayOutputStream(); workbook.write(byout); byout.close(); CardRequest cr = new CardRequest(); cr.setRequestRefNum(getActiveUser().getPartner().getCode() + "-" + password); cr.setAdditionalComment(getRequestComment()); cr.setCrt_dt(new Date()); cr.setExcelFile(byout.toByteArray()); cr.setPartner(getActiveUser().getPartner()); cr.setRequest_dt(new Date()); cr.setRequestedBy(getActiveUser()); cr.setRequestType("LOAD-CARDS"); cr.setStatus("PENDING"); GeneralDAO gDAO = new GeneralDAO(); gDAO.startTransaction(); boolean ret = gDAO.save(cr); if (ret) { gDAO.commit(); setRequestComment(null); setMyPendingCardCancelRequests(null); curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "Request submitted successfully!")); // Send email to user that submitted that their request is been treated String body = "<html><body><p>Dear " + getActiveUser().getFullname() + ",</p><p>Your request to load cards has been recieved and will be treated as soon as possible. You will be notified of every progress.</p><p>Regards<br/>Fuel Card Platform</p></body></html>"; Emailer.sendEmail("fuelcard@sattrakservices.com", new String[] { getActiveUser().getEmail() }, "Card Load Request - " + cr.getRequestRefNum() + " Received", body); // Send email to sattrak that request is submitted byte[] doc = cr.getExcelFile(); String body2 = "<html><body><p>Hello,</p><p>A request to load cards has been submitted. The document is attached.</p><p>Regards<br/>Fuel Card Platform</p></body></html>"; if (getSattrakPartner() != null && getSattrakPartner().getContactEmails() != null && getSattrakPartner().getContactEmails().trim().length() > 0) { String[] to = getSattrakPartner().getContactEmails().split(","); Emailer.sendEmail("fuelcard@sattrakservices.com", to, "Card Load Request - " + cr.getRequestRefNum() + " Submitted", body2, doc, cr.getRequestRefNum() + ".xls", "application/vnd.ms-excel"); } } else { gDAO.rollback(); curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", gDAO.getMessage())); } gDAO.destroy(); } else { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed", "Excel document is not valid!")); } } catch (Exception ex) { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Severe", "Please upload an excel document! Error: " + ex.getMessage())); } } else { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed", "Please upload an excel document!")); } }
From source file:com.dexter.fuelcard.mbean.UserMBean.java
public void cancelCards() { FacesContext curContext = FacesContextImpl.getCurrentInstance(); if (getUploadItem() != null) { try {/*from www . ja v a2 s. c o m*/ HSSFWorkbook workbook = new HSSFWorkbook(getUploadItem().getInputstream()); int sheetCount = workbook.getNumberOfSheets(); if (sheetCount >= 1) { String password = getRandomDigitPassword(); HSSFSheet sheet = workbook.getSheetAt(0); // first sheet should be the main sheet sheet.protectSheet(password); ByteArrayOutputStream byout = new ByteArrayOutputStream(); workbook.write(byout); byout.close(); CardRequest cr = new CardRequest(); cr.setRequestRefNum(getActiveUser().getPartner().getCode() + "-" + password); cr.setAdditionalComment(getRequestComment()); cr.setCrt_dt(new Date()); cr.setExcelFile(byout.toByteArray()); cr.setPartner(getActiveUser().getPartner()); cr.setRequest_dt(new Date()); cr.setRequestedBy(getActiveUser()); cr.setRequestType("CANCEL-CARDS"); cr.setStatus("PENDING"); GeneralDAO gDAO = new GeneralDAO(); gDAO.startTransaction(); boolean ret = gDAO.save(cr); if (ret) { gDAO.commit(); setRequestComment(null); setMyPendingCardCancelRequests(null); curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "Request submitted successfully!")); // Send email to user that submitted that their request is been treated String body = "<html><body><p>Dear " + getActiveUser().getFullname() + ",</p><p>Your request to decommission cards has been recieved and will be treated as soon as possible. You will be notified of every progress.</p><p>Regards<br/>Fuel Card Platform</p></body></html>"; Emailer.sendEmail("fuelcard@sattrakservices.com", new String[] { getActiveUser().getEmail() }, "Card Decommission Request - " + cr.getRequestRefNum() + " Received", body); // Send email to sattrak that request is submitted byte[] doc = cr.getExcelFile(); String body2 = "<html><body><p>Hello,</p><p>A request to decommission cards has been submitted. The document is attached.</p><p>Regards<br/>Fuel Card Platform</p></body></html>"; if (getSattrakPartner() != null && getSattrakPartner().getContactEmails() != null && getSattrakPartner().getContactEmails().trim().length() > 0) { String[] to = getSattrakPartner().getContactEmails().split(","); Emailer.sendEmail("fuelcard@sattrakservices.com", to, "Card Decommission Request - " + cr.getRequestRefNum() + " Submitted", body2, doc, cr.getRequestRefNum() + ".xls", "application/vnd.ms-excel"); } } else { gDAO.rollback(); curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", gDAO.getMessage())); } gDAO.destroy(); } else { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed", "Excel document is not valid!")); } } catch (Exception ex) { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Severe", "Please upload an excel document! Error: " + ex.getMessage())); } } else { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed", "Please upload an excel document!")); } }
From source file:com.dexter.fuelcard.mbean.UserMBean.java
public void orderCards() { FacesContext curContext = FacesContextImpl.getCurrentInstance(); if (getUploadItem() != null) { try {/*from ww w .ja va 2s . c om*/ HSSFWorkbook workbook = new HSSFWorkbook(getUploadItem().getInputstream()); int sheetCount = workbook.getNumberOfSheets(); if (sheetCount >= 2) { String password = getRandomDigitPassword(); HSSFSheet sheet = workbook.getSheetAt(0); // first sheet should be the main sheet sheet.protectSheet(password); ByteArrayOutputStream byout = new ByteArrayOutputStream(); workbook.write(byout); byout.close(); CardRequest cr = new CardRequest(); cr.setRequestRefNum(getActiveUser().getPartner().getCode() + "-" + password); cr.setAdditionalComment(getRequestComment()); cr.setCrt_dt(new Date()); cr.setExcelFile(byout.toByteArray()); cr.setPartner(getActiveUser().getPartner()); cr.setRequest_dt(new Date()); cr.setRequestedBy(getActiveUser()); cr.setRequestType("ORDER-CARDS"); cr.setStatus("PENDING"); GeneralDAO gDAO = new GeneralDAO(); gDAO.startTransaction(); boolean ret = gDAO.save(cr); if (ret) { gDAO.commit(); setRequestComment(null); setMyPendingCardOrderRequests(null); curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "Request submitted successfully!")); // Send email to user that submitted that their request is been treated String body = "<html><body><p>Dear " + getActiveUser().getFullname() + ",</p><p>Your request to order cards has been recieved and will be treated as soon as possible. You will be notified of every progress.</p><p>Regards<br/>Fuel Card Platform</p></body></html>"; Emailer.sendEmail("fuelcard@sattrakservices.com", new String[] { getActiveUser().getEmail() }, "Card Order Request - " + cr.getRequestRefNum() + " Received", body); // Send email to sattrak that request is submitted byte[] doc = cr.getExcelFile(); String body2 = "<html><body><p>Hello,</p><p>A request to order cards has been submitted. The document is attached.</p><p>Regards<br/>Fuel Card Platform</p></body></html>"; if (getSattrakPartner() != null && getSattrakPartner().getContactEmails() != null && getSattrakPartner().getContactEmails().trim().length() > 0) { String[] to = getSattrakPartner().getContactEmails().split(","); Emailer.sendEmail("fuelcard@sattrakservices.com", to, "Card Order Request - " + cr.getRequestRefNum() + " Submitted", body2, doc, cr.getRequestRefNum() + ".xls", "application/vnd.ms-excel"); } } else { gDAO.rollback(); curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", gDAO.getMessage())); } gDAO.destroy(); } else { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed", "Excel document is not valid!")); } } catch (Exception ex) { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Severe", "Please upload an excel document! Error: " + ex.getMessage())); } } else { curContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed", "Please upload an excel document!")); } }
From source file:com.dtrules.compiler.excel.util.ImportRuleSets.java
License:Apache License
/** * Reads the decision table out of an Excel spreadsheet and generates the * approriate XML. //from w w w . j av a2s . com * @param file * @param sb * @return true if at least one decision table was found in this file * @throws Exception */ public boolean convertDecisionTable(StringBuffer data, File file, XMLPrinter out, int depth) throws Exception { if (!(file.getName().endsWith(".xls"))) return false; InputStream input = new FileInputStream(file.getAbsolutePath()); POIFSFileSystem fs = new POIFSFileSystem(input); HSSFWorkbook wb = new HSSFWorkbook(fs); boolean tablefound = false; CountsAreDirty = false; for (int i = 0; i < wb.getNumberOfSheets(); i++) { tablefound |= convertOneSheet(data, file.getName(), wb.getSheetAt(i), out, depth); } if (CountsAreDirty == true) { System.out.println( "Line Numbers on Contexts, Initial Actions, Conditions, and/or Actions are incorrect.\r\n" + "A Corrected version has been written to the decision table directory"); OutputStream output = new FileOutputStream(file.getAbsolutePath() + ".fixedCounts"); wb.write(output); } else { (new File(file.getAbsolutePath() + ".fixedCounts")).delete(); } return tablefound; }
From source file:com.dv.util.DVExcelIO.java
License:Open Source License
public static boolean exportIntoExcel(String fullExcelFileName, String sheetName, Vector cols, Vector rows) { boolean isExportFine = true; HSSFWorkbook hsswb = null; HSSFSheet hsssh = null;/*from ww w . j a v a2 s . c o m*/ HSSFRow row = null; try { File excel = new File(fullExcelFileName); if (!excel.exists()) { hsswb = new HSSFWorkbook(); hsssh = hsswb.createSheet(sheetName); hsssh.setDefaultRowHeight((short) 10); hsssh.setDefaultColumnWidth(20); } else { hsswb = new HSSFWorkbook(new FileInputStream(excel)); hsssh = hsswb.createSheet(sheetName); hsssh.setDefaultRowHeight((short) 10); hsssh.setDefaultColumnWidth(20); } row = hsssh.createRow((short) 2); HSSFCellStyle style = hsswb.createCellStyle(); style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setBottomBorderColor(HSSFColor.BLACK.index); style.setLeftBorderColor(HSSFColor.BLACK.index); style.setTopBorderColor(HSSFColor.BLACK.index); style.setRightBorderColor(HSSFColor.BLACK.index); for (int i = 0; i < cols.size(); i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(cols.get(i).toString()); cell.setCellStyle(style); } HSSFCellStyle style1 = hsswb.createCellStyle(); style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); style1.setBorderLeft(HSSFCellStyle.BORDER_THIN); style1.setBorderRight(HSSFCellStyle.BORDER_THIN); style1.setBorderTop(HSSFCellStyle.BORDER_THIN); style1.setBottomBorderColor(HSSFColor.BLACK.index); style1.setLeftBorderColor(HSSFColor.BLACK.index); style1.setTopBorderColor(HSSFColor.BLACK.index); style1.setRightBorderColor(HSSFColor.BLACK.index); for (int i = 3; i <= rows.size() + 2; i++) { row = hsssh.createRow((short) i); for (int j = 0; j < cols.size(); j++) { HSSFCell cell = row.createCell(j); cell.setCellValue(((Vector) rows.elementAt(i - 3)).get(j).toString()); cell.setCellStyle(style1); } } FileOutputStream fOut = new FileOutputStream(excel); hsswb.write(fOut); fOut.flush(); fOut.close(); } catch (IOException e) { DVLOG.setErrorLog(DVExcelIO.class.getName(), e); return false; } catch (IllegalArgumentException e) { DVLOG.setErrorLog(DVExcelIO.class.getName(), e); return false; } catch (Exception e) { DVLOG.setErrorLog(DVExcelIO.class.getName(), e); return false; } return isExportFine; }
From source file:com.dv.util.DVExcelIO.java
License:Open Source License
public static boolean exportBatchResultIntoExcel(String fullExcelFileName, String sheetName, HashMap<String, Vector> colsMap, HashMap<String, Vector> rowsMap) { HSSFWorkbook hsswb = null; HSSFSheet hsssh = null;/*from ww w . j a v a 2 s .c om*/ HSSFRow row = null; Vector cols = new Vector(); Vector rows = new Vector(); try { File excel = new File(fullExcelFileName); if (!excel.exists()) { hsswb = new HSSFWorkbook(); hsssh = hsswb.createSheet(sheetName); hsssh.setDefaultRowHeight((short) 10); hsssh.setDefaultColumnWidth(20); } else { hsswb = new HSSFWorkbook(new FileInputStream(excel)); hsssh = hsswb.createSheet(sheetName); hsssh.setDefaultRowHeight((short) 10); hsssh.setDefaultColumnWidth(20); } int rowCount = 1; for (int k = 0; k < colsMap.size(); k++) { cols = colsMap.get(String.valueOf(k)); rows = rowsMap.get(String.valueOf(k)); rowCount = rowCount + 1; row = hsssh.createRow((short) (rowCount)); HSSFCellStyle style = hsswb.createCellStyle(); style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setBottomBorderColor(HSSFColor.BLACK.index); style.setLeftBorderColor(HSSFColor.BLACK.index); style.setTopBorderColor(HSSFColor.BLACK.index); style.setRightBorderColor(HSSFColor.BLACK.index); for (int i = 0; i < cols.size(); i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(cols.get(i).toString()); cell.setCellStyle(style); } HSSFCellStyle style1 = hsswb.createCellStyle(); style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); style1.setBorderLeft(HSSFCellStyle.BORDER_THIN); style1.setBorderRight(HSSFCellStyle.BORDER_THIN); style1.setBorderTop(HSSFCellStyle.BORDER_THIN); style1.setBottomBorderColor(HSSFColor.BLACK.index); style1.setLeftBorderColor(HSSFColor.BLACK.index); style1.setTopBorderColor(HSSFColor.BLACK.index); style1.setRightBorderColor(HSSFColor.BLACK.index); int loop = rowCount; for (int i = 1 + loop; i <= rows.size() + loop; i++) { row = hsssh.createRow((short) i); for (int j = 0; j < cols.size(); j++) { HSSFCell cell = row.createCell(j); cell.setCellValue(((Vector) rows.elementAt(i - (1 + loop))).get(j).toString()); cell.setCellStyle(style1); } rowCount++; } } FileOutputStream fOut = new FileOutputStream(excel); hsswb.write(fOut); fOut.flush(); fOut.close(); } catch (IOException e) { DVLOG.setErrorLog(DVExcelIO.class.getName(), e); return false; } catch (IllegalArgumentException e) { DVLOG.setErrorLog(DVExcelIO.class.getName(), e); return false; } catch (Exception e) { DVLOG.setErrorLog(DVExcelIO.class.getName(), e); return false; } return true; }
From source file:com.dv.util.DVExcelIO.java
License:Open Source License
public static Vector setExcelBHTIMFormat(String fullExcelFileName, String sheetName, int rowNumbers) { File file = new File(fullExcelFileName); FileInputStream in = null;/*from ww w . ja v a2 s . co m*/ Vector cols = new Vector(); try { in = new FileInputStream(file); HSSFWorkbook workbook = new HSSFWorkbook(in); HSSFSheet sheet = workbook.getSheet(sheetName); HSSFRow row = null; HSSFCell cell = null; for (int i = 2; i < rowNumbers; i++) { row = sheet.getRow(i); cell = row.getCell(4);//9 for cty String ppp = cell.toString().trim(); cell = row.getCell(9); String fff = cell.toString().trim(); if (!ppp.equals("")) { String contents = "Verify from FMS side for " + ppp + "(" + fff + ")"; // cols.addElement(contents); row.getCell(16).setCellValue(contents); } else { return null; } } FileOutputStream fOut = new FileOutputStream(file); workbook.write(fOut); fOut.flush(); fOut.close(); } catch (Exception eee) { } return cols; }
From source file:com.eastsoft.ui.MainUI.java
License:Open Source License
void savePrintInfoToExcel(recordInfo recordinfor, int printFormat) { if (printFormat != 0) { HSSFWorkbook wb = null; File printRecord = new File("?.xls"); if (!printRecord.exists()) { wb = new HSSFWorkbook(); HSSFSheet sheet1 = wb.createSheet("sheet1"); HSSFRow row = sheet1.createRow(0); row.createCell((short) 0).setCellValue("? "); row.createCell((short) 1).setCellValue(" "); row.createCell((short) 2).setCellValue("?? "); row.createCell((short) 3).setCellValue("?? "); row.createCell((short) 4).setCellValue("Aid "); row.createCell((short) 5).setCellValue("? "); HSSFRow row1 = sheet1.createRow(sheet1.getLastRowNum() + 1); row1.createCell((short) 0).setCellValue(recordinfor.getDate()); row1.createCell((short) 1).setCellValue(recordinfor.getProductSerialNO()); row1.createCell((short) 2).setCellValue(recordinfor.getDevice()); row1.createCell((short) 3).setCellValue(recordinfor.getProduct()); row1.createCell((short) 4).setCellValue(recordinfor.getAid()); row1.createCell((short) 5).setCellValue(recordinfor.getPasswd()); } else {/*from w w w . j a v a2s .c o m*/ FileInputStream fs = null; try { fs = new FileInputStream(printRecord); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } POIFSFileSystem ps = null; try { ps = new POIFSFileSystem(fs); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { wb = new HSSFWorkbook(ps); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } HSSFSheet sheet = wb.getSheetAt(0); // ?cell,Rows 0(Create a row and put some cells // in // it. Rows are 0 based.) HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1); row.createCell((short) 0).setCellValue(recordinfor.getDate()); row.createCell((short) 1).setCellValue(recordinfor.getProductSerialNO()); row.createCell((short) 2).setCellValue(recordinfor.getDevice()); row.createCell((short) 3).setCellValue(recordinfor.getProduct()); row.createCell((short) 4).setCellValue(recordinfor.getAid()); row.createCell((short) 5).setCellValue(recordinfor.getPasswd()); } FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(printRecord); } catch (FileNotFoundException e) { // TODO Auto-generated catch block appendTextareaText(jTextArea_status, "\n?.xls ??"); JOptionPane.showMessageDialog(getParent(), "?.xls ??", "?.xls", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } try { wb.write(fileOut); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fileOut.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.efficio.fieldbook.service.ExportExcelServiceImpl.java
License:Open Source License
public FileOutputStream exportFieldMapToExcel(String fileName, UserFieldmap userFieldMap) throws FieldbookException { Locale locale = LocaleContextHolder.getLocale(); boolean isTrial = userFieldMap.isTrial(); // Summary of Trial/Nursery, Field and Planting Details String summaryOfFieldbookFieldPlantingDetailsLabel = messageSource .getMessage("fieldmap.header.summary.for.trial", null, locale); //SUMMARY OF TRIAL, FIELD AND PLANTING DETAILS String selectedFieldbookLabel = messageSource.getMessage("fieldmap.trial.selected.trial", null, locale); //Selected Trial: if (!isTrial) { summaryOfFieldbookFieldPlantingDetailsLabel = messageSource .getMessage("fieldmap.header.summary.for.nursery", null, locale); //SUMMARY OF NURSERY, FIELD AND PLANTING DETAILS selectedFieldbookLabel = messageSource.getMessage("fieldmap.nursery.selected.nursery", null, locale); //Selected Nursery: }// w w w. j a v a2 s . c o m String selectedFieldbookValue = userFieldMap.getBlockName(); String orderHeader = messageSource.getMessage("fieldmap.trial.order", null, locale); String studyHeader = messageSource.getMessage((isTrial ? "fieldmap.trial" : "fieldmap.nursery"), null, locale); String instanceHeader = messageSource.getMessage("fieldmap.trial.instance", null, locale); String entriesCountHeader = messageSource.getMessage("fieldmap.trial.entry.count", null, locale); String repsCountHeader = messageSource.getMessage("fieldmap.trial.reps.count", null, locale); String plotsNeededHeader = messageSource.getMessage("fieldmap.trial.plots.needed", null, locale); String totalPlotsHeader = messageSource.getMessage("fieldmap.trial.total.number.of.plots", null, locale); String datasetNameHeader = messageSource.getMessage("fieldmap.nursery.dataset", null, locale); // Field And Block Details String fieldAndBlockDetailsLabel = messageSource.getMessage("fieldmap.trial.field.and.block.details", null, locale); //FIELD AND BLOCK DETAILS String fieldLocationLabel = messageSource.getMessage("fieldmap.label.field.location", null, locale); //Field Location String fieldLocationValue = userFieldMap.getLocationName(); String fieldNameLabel = messageSource.getMessage("fieldmap.label.field.name", null, locale); //Field Name String fieldNameValue = userFieldMap.getFieldName(); String blockNameLabel = messageSource.getMessage("fieldmap.label.block.name", null, locale); //Block Name String blockNameValue = userFieldMap.getBlockName(); // Row, Range & Plot Details String rowRangePlotDetailsLabel = messageSource.getMessage("fieldmap.trial.row.and.range.and.plot.details", null, locale); //ROW, RANGE AND PLOT DETAILS String blockCapacityLabel = messageSource.getMessage("fieldmap.label.block.capacity", null, locale); //Block Capacity String blockCapacityValue = userFieldMap.getBlockCapacityString(messageSource); //e.g. "10 Columns, 10 Ranges" String rowsPerPlotLabel = messageSource.getMessage("fieldmap.label.rows.per.plot", null, locale); //Rows per Plot int rowsPerPlotValue = userFieldMap.getNumberOfRowsPerPlot(); String columnsLabel = messageSource.getMessage("fieldmap.label.columns", null, locale); //Columns Integer columnsValue = userFieldMap.getNumberOfColumnsInBlock(); // 10 String machineCapacityLabel = messageSource.getMessage("fieldmap.label.row.capacity.machine", null, locale); //machine row capacity Integer machineCapacityValue = userFieldMap.getMachineRowCapacity(); //Planting Details String plantingDetailsLabel = messageSource.getMessage("fieldmap.header.planting.details", null, locale); //PLANTING DETAILS String startingCoordinatesLabel = messageSource.getMessage("fieldmap.label.starting.coordinates", null, locale); //Starting Coordinates String startingCoordinatesValue = userFieldMap.getStartingCoordinateString(messageSource); // Column 1, Range 1 String plantingOrderLabel = messageSource.getMessage("fieldmap.label.planting.order", null, locale); //Planting Order String plantingOrderValue = userFieldMap.getPlantingOrderString(messageSource); //"Row/Column" or "Serpentine" // FieldMap String fieldMapLabel = messageSource.getMessage("fieldmap.header.fieldmap", null, locale); //FIELD MAP String rowsLabel = messageSource.getMessage("fieldmap.label.rows", null, locale); //Rows String columnLabel = messageSource.getMessage("fieldmap.label.capitalized.column", null, locale); //Column String rangeLabel = messageSource.getMessage("fieldmap.label.capitalized.range", null, locale); //Range try { //Create workbook HSSFWorkbook workbook = new HSSFWorkbook(); String summaryLabelSheet = messageSource.getMessage("fieldmap.header.excel.summary", null, locale); Sheet summarySheet = workbook.createSheet(summaryLabelSheet); Sheet fieldMapSheet = workbook.createSheet(fieldMapLabel); CellStyle labelStyle = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); labelStyle.setFont(font); CellStyle wrapStyle = workbook.createCellStyle(); wrapStyle.setWrapText(true); wrapStyle.setAlignment(CellStyle.ALIGN_CENTER); CellStyle mainHeaderStyle = workbook.createCellStyle(); HSSFPalette palette = workbook.getCustomPalette(); // get the color which most closely matches the color you want to use HSSFColor myColor = palette.findSimilarColor(179, 165, 165); // get the palette index of that color short palIndex = myColor.getIndex(); // code to get the style for the cell goes here mainHeaderStyle.setFillForegroundColor(palIndex); mainHeaderStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); CellStyle mainSubHeaderStyle = workbook.createCellStyle(); HSSFPalette paletteSubHeader = workbook.getCustomPalette(); // get the color which most closely matches the color you want to use HSSFColor myColorSubHeader = paletteSubHeader.findSimilarColor(190, 190, 186); // get the palette index of that color short palIndexSubHeader = myColorSubHeader.getIndex(); // code to get the style for the cell goes here mainSubHeaderStyle.setFillForegroundColor(palIndexSubHeader); mainSubHeaderStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); mainSubHeaderStyle.setAlignment(CellStyle.ALIGN_CENTER); int rowIndex = 0; int columnIndex = 0; // Create Header Information // Row 1: SUMMARY OF TRIAL, FIELD AND PLANTING DETAILS CellStyle headerLabelStyle = workbook.createCellStyle(); font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); headerLabelStyle.setFont(font); headerLabelStyle.setAlignment(CellStyle.ALIGN_CENTER); Row row = summarySheet.createRow(rowIndex++); Cell summaryCell = row.createCell(columnIndex); summaryCell.setCellValue(summaryOfFieldbookFieldPlantingDetailsLabel); summaryCell.setCellStyle(headerLabelStyle); summarySheet.addMergedRegion(new CellRangeAddress(rowIndex - 1, //first row (0-based) rowIndex - 1, //last row (0-based) columnIndex, //first column (0-based) columnIndex + 5 //last column (0-based) )); // Row 2: Space row = summarySheet.createRow(rowIndex++); // Row 3: Fieldbook Name, Entries, Reps, Plots row = summarySheet.createRow(rowIndex++); // Selected Trial : [Fieldbook Name] TABLE SECTION Cell labelCell = row.createCell(columnIndex++); labelCell.setCellValue(selectedFieldbookLabel); row = summarySheet.createRow(rowIndex++); columnIndex = 0; Cell headerCell = row.createCell(columnIndex++); headerCell.setCellValue(orderHeader); headerCell.setCellStyle(labelStyle); headerCell = row.createCell(columnIndex++); headerCell.setCellValue(studyHeader); headerCell.setCellStyle(labelStyle); if (isTrial) { headerCell = row.createCell(columnIndex++); headerCell.setCellValue(instanceHeader); headerCell.setCellStyle(labelStyle); headerCell = row.createCell(columnIndex++); headerCell.setCellValue(entriesCountHeader); headerCell.setCellStyle(labelStyle); headerCell = row.createCell(columnIndex++); headerCell.setCellValue(repsCountHeader); headerCell.setCellStyle(labelStyle); } else { headerCell = row.createCell(columnIndex++); headerCell.setCellValue(datasetNameHeader); headerCell.setCellStyle(labelStyle); } headerCell = row.createCell(columnIndex++); headerCell.setCellValue(plotsNeededHeader); headerCell.setCellStyle(labelStyle); for (SelectedFieldmapRow rec : userFieldMap.getSelectedFieldmapList().getRows()) { row = summarySheet.createRow(rowIndex++); columnIndex = 0; row.createCell(columnIndex++).setCellValue(rec.getOrder()); row.createCell(columnIndex++).setCellValue(rec.getStudyName()); if (isTrial) { row.createCell(columnIndex++).setCellValue(rec.getTrialInstanceNo()); row.createCell(columnIndex++).setCellValue(String.valueOf(rec.getEntryCount())); row.createCell(columnIndex++).setCellValue(String.valueOf(rec.getRepCount())); row.createCell(columnIndex++).setCellValue(String.valueOf(rec.getPlotCount())); } else { row.createCell(columnIndex++).setCellValue(rec.getDatasetName()); row.createCell(columnIndex++).setCellValue(String.valueOf(rec.getEntryCount())); } } row = summarySheet.createRow(rowIndex++); columnIndex = 0; headerCell = row.createCell(columnIndex++); headerCell.setCellValue(totalPlotsHeader); headerCell.setCellStyle(labelStyle); row.createCell(columnIndex++) .setCellValue(String.valueOf(userFieldMap.getSelectedFieldmapList().getTotalNumberOfPlots())); // Row 4: Space row = summarySheet.createRow(rowIndex++); // Row 5: Header - Details Heading row = summarySheet.createRow(rowIndex++); columnIndex = 0; labelCell = row.createCell(columnIndex++); labelCell.setCellValue(fieldAndBlockDetailsLabel); labelCell.setCellStyle(headerLabelStyle); summarySheet.addMergedRegion(new CellRangeAddress(rowIndex - 1, //first row (0-based) rowIndex - 1, //last row (0-based) columnIndex - 1, //first column (0-based) columnIndex //last column (0-based) )); row.createCell(columnIndex++); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(rowRangePlotDetailsLabel); labelCell.setCellStyle(headerLabelStyle); summarySheet.addMergedRegion(new CellRangeAddress(rowIndex - 1, //first row (0-based) rowIndex - 1, //last row (0-based) columnIndex - 1, //first column (0-based) columnIndex //last column (0-based) )); row.createCell(columnIndex++); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(plantingDetailsLabel); labelCell.setCellStyle(headerLabelStyle); summarySheet.addMergedRegion(new CellRangeAddress(rowIndex - 1, //first row (0-based) rowIndex - 1, //last row (0-based) columnIndex - 1, //first column (0-based) columnIndex //last column (0-based) )); row.createCell(columnIndex++); //Row 6: Field Location, Block Capacity, Starting Coordinates row = summarySheet.createRow(rowIndex++); columnIndex = 0; labelCell = row.createCell(columnIndex++); labelCell.setCellValue(fieldLocationLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(fieldLocationValue); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(blockCapacityLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(blockCapacityValue); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(startingCoordinatesLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(startingCoordinatesValue); // Row 7: Field Name, Rows Per Plot, Planting Order row = summarySheet.createRow(rowIndex++); columnIndex = 0; labelCell = row.createCell(columnIndex++); labelCell.setCellValue(fieldNameLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(fieldNameValue); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(rowsPerPlotLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(String.valueOf(rowsPerPlotValue)); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(plantingOrderLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(plantingOrderValue); // Row 8: Block Name, Columns row = summarySheet.createRow(rowIndex++); columnIndex = 0; labelCell = row.createCell(columnIndex++); labelCell.setCellValue(blockNameLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(blockNameValue); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(columnsLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(String.valueOf(columnsValue)); labelCell = row.createCell(columnIndex++); labelCell.setCellValue(machineCapacityLabel); labelCell.setCellStyle(labelStyle); row.createCell(columnIndex++).setCellValue(String.valueOf(machineCapacityValue)); // Row 9: Space row = summarySheet.createRow(rowIndex++); for (int columnsResize = 0; columnsResize < columnIndex; columnsResize++) { summarySheet.autoSizeColumn(columnsResize); } // Get FieldMap data //we reset the row index rowIndex = 0; // Row 10: FIELD MAP row = fieldMapSheet.createRow(rowIndex++); columnIndex = 0; labelCell = row.createCell(columnIndex++); labelCell.setCellValue(fieldMapLabel); labelCell.setCellStyle(labelStyle); // Row 11: Space row = fieldMapSheet.createRow(rowIndex++); Plot[][] plots = userFieldMap.getFieldmap(); int range = userFieldMap.getNumberOfRangesInBlock(); int col = userFieldMap.getNumberOfColumnsInBlock(); int rowsPerPlot = userFieldMap.getNumberOfRowsPerPlot(); int machineRowCapacity = userFieldMap.getMachineRowCapacity(); int rows = userFieldMap.getNumberOfRowsInBlock(); boolean isSerpentine = userFieldMap.getPlantingOrder() == 2; for (int j = range - 1; j >= 0; j--) { if (j == range - 1) { // TOP TABLE LABELS // Row 12: Rows Header rowIndex = printRowHeader(fieldMapSheet, userFieldMap.getNumberOfRowsInBlock(), rowIndex, rowsLabel, mainHeaderStyle, mainSubHeaderStyle); // Row 13: UP, DOWN Direction rowIndex = printDirectionHeader(fieldMapSheet, plots, j, rows, rowIndex, machineRowCapacity, mainHeaderStyle, mainSubHeaderStyle, isSerpentine); // Row 14: Column labels rowIndex = printColumnHeader(fieldMapSheet, col, rowIndex, columnLabel, rowsPerPlot, mainHeaderStyle, mainSubHeaderStyle); } // Rows 15 onwards: Ranges and Row Data row = fieldMapSheet.createRow(rowIndex); row.setHeightInPoints(45); columnIndex = 0; int rangeValue = j + 1; Cell cellRange = row.createCell(columnIndex++); cellRange.setCellValue(rangeLabel + " " + rangeValue); cellRange.setCellStyle(mainSubHeaderStyle); for (int i = 0; i < col; i++) { String displayString = plots[i][j].getDisplayString().replace("<br/>", "\n"); if (plots[i][j].isPlotDeleted()) { displayString = " X "; } Cell dataCell = row.createCell(columnIndex++); //dataCell.setCellValue(displayString); dataCell.setCellValue(new HSSFRichTextString(displayString)); dataCell.setCellStyle(wrapStyle); //row.createCell(columnIndex).setCellValue(""); for (int k = 0; k < rowsPerPlot - 1; k++) { row.createCell(columnIndex++).setCellValue(""); } fieldMapSheet.addMergedRegion(new CellRangeAddress(rowIndex, //first row (0-based) rowIndex, //last row (0-based) columnIndex - rowsPerPlot, //first column (0-based) columnIndex - 1 //last column (0-based) )); //columnIndex++; } rowIndex++; if (j == 0) { // BOTTOM TABLE LABELS rowIndex = printColumnHeader(fieldMapSheet, col, rowIndex, columnLabel, rowsPerPlot, mainHeaderStyle, mainSubHeaderStyle); rowIndex = printDirectionHeader(fieldMapSheet, plots, j, rows, rowIndex, machineRowCapacity, mainHeaderStyle, mainSubHeaderStyle, isSerpentine); rowIndex = printRowHeader(fieldMapSheet, userFieldMap.getNumberOfRowsInBlock(), rowIndex, rowsLabel, mainHeaderStyle, mainSubHeaderStyle); } } //Write the excel file FileOutputStream fileOutputStream = new FileOutputStream(fileName); workbook.write(fileOutputStream); fileOutputStream.close(); return fileOutputStream; } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); throw new FieldbookException("Error writing to file: " + fileName, e); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new FieldbookException("Error writing to file: " + fileName, e); } }
From source file:com.efficio.fieldbook.service.LabelPrintingServiceImpl.java
License:Open Source License
@Override public String generateXlSLabels(List<StudyTrialInstanceInfo> trialInstances, UserLabelPrinting userLabelPrinting, ByteArrayOutputStream baos) throws MiddlewareQueryException { int pageSizeId = Integer.parseInt(userLabelPrinting.getSizeOfLabelSheet()); int numberOfLabelPerRow = Integer.parseInt(userLabelPrinting.getNumberOfLabelPerRow()); int numberofRowsPerPageOfLabel = Integer.parseInt(userLabelPrinting.getNumberOfRowsPerPageOfLabel()); int totalPerPage = numberOfLabelPerRow * numberofRowsPerPageOfLabel; String leftSelectedFields = userLabelPrinting.getLeftSelectedLabelFields(); String rightSelectedFields = userLabelPrinting.getRightSelectedLabelFields(); String barcodeNeeded = userLabelPrinting.getBarcodeNeeded(); String firstBarcodeField = userLabelPrinting.getFirstBarcodeField(); String secondBarcodeField = userLabelPrinting.getSecondBarcodeField(); String thirdBarcodeField = userLabelPrinting.getThirdBarcodeField(); String currentDate = DateUtil.getCurrentDate(); //String fileName = currentDate + ".xls"; String fileName = userLabelPrinting.getFilenameDLLocation(); try {//from w ww .j a v a 2 s . c om HSSFWorkbook workbook = new HSSFWorkbook(); String sheetName = cleanSheetName(userLabelPrinting.getName()); if (sheetName == null) sheetName = "Labels"; Sheet labelPrintingSheet = workbook.createSheet(sheetName); CellStyle labelStyle = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); labelStyle.setFont(font); CellStyle wrapStyle = workbook.createCellStyle(); wrapStyle.setWrapText(true); wrapStyle.setAlignment(CellStyle.ALIGN_CENTER); CellStyle mainHeaderStyle = workbook.createCellStyle(); HSSFPalette palette = workbook.getCustomPalette(); // get the color which most closely matches the color you want to use HSSFColor myColor = palette.findSimilarColor(179, 165, 165); // get the palette index of that color short palIndex = myColor.getIndex(); // code to get the style for the cell goes here mainHeaderStyle.setFillForegroundColor(palIndex); mainHeaderStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); CellStyle mainSubHeaderStyle = workbook.createCellStyle(); HSSFPalette paletteSubHeader = workbook.getCustomPalette(); // get the color which most closely matches the color you want to use HSSFColor myColorSubHeader = paletteSubHeader.findSimilarColor(190, 190, 186); // get the palette index of that color short palIndexSubHeader = myColorSubHeader.getIndex(); // code to get the style for the cell goes here mainSubHeaderStyle.setFillForegroundColor(palIndexSubHeader); mainSubHeaderStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); mainSubHeaderStyle.setAlignment(CellStyle.ALIGN_CENTER); int rowIndex = 0; int columnIndex = 0; // Create Header Information // Row 1: SUMMARY OF TRIAL, FIELD AND PLANTING DETAILS Row row = labelPrintingSheet.createRow(rowIndex++); //we add all the selected fields header StringTokenizer token = new StringTokenizer(leftSelectedFields, ","); while (token.hasMoreTokens()) { String headerId = token.nextToken(); String headerName = getHeader(headerId); Cell summaryCell = row.createCell(columnIndex++); summaryCell.setCellValue(headerName); summaryCell.setCellStyle(labelStyle); } token = new StringTokenizer(rightSelectedFields, ","); while (token.hasMoreTokens()) { String headerId = token.nextToken(); String headerName = getHeader(headerId); Cell summaryCell = row.createCell(columnIndex++); summaryCell.setCellValue(headerName); summaryCell.setCellStyle(labelStyle); } //we populate the info now int i = 0; for (StudyTrialInstanceInfo trialInstance : trialInstances) { FieldMapTrialInstanceInfo fieldMapTrialInstanceInfo = trialInstance.getTrialInstance(); Map<String, String> moreFieldInfo = new HashMap<String, String>(); moreFieldInfo.put("locationName", fieldMapTrialInstanceInfo.getLocationName()); moreFieldInfo.put("blockName", fieldMapTrialInstanceInfo.getBlockName()); moreFieldInfo.put("selectedName", trialInstance.getFieldbookName()); moreFieldInfo.put("trialInstanceNumber", fieldMapTrialInstanceInfo.getTrialInstanceNo()); for (FieldMapLabel fieldMapLabel : fieldMapTrialInstanceInfo.getFieldMapLabels()) { row = labelPrintingSheet.createRow(rowIndex++); columnIndex = 0; i++; token = new StringTokenizer(leftSelectedFields, ","); while (token.hasMoreTokens()) { String headerId = token.nextToken(); String leftText = getSpecificInfo(moreFieldInfo, fieldMapLabel, headerId); Cell summaryCell = row.createCell(columnIndex++); summaryCell.setCellValue(leftText); //summaryCell.setCellStyle(labelStyle); } token = new StringTokenizer(rightSelectedFields, ","); while (token.hasMoreTokens()) { String headerId = token.nextToken(); String rightText = getSpecificInfo(moreFieldInfo, fieldMapLabel, headerId); Cell summaryCell = row.createCell(columnIndex++); summaryCell.setCellValue(rightText); //summaryCell.setCellStyle(labelStyle); } } } for (int columnPosition = 0; columnPosition < columnIndex; columnPosition++) { labelPrintingSheet.autoSizeColumn((short) (columnPosition)); } //Write the excel file FileOutputStream fileOutputStream = new FileOutputStream(fileName); //workbook.write(baos); workbook.write(fileOutputStream); fileOutputStream.close(); //return fileOutputStream; } catch (Exception e) { LOG.error(e.getMessage(), e); } return fileName; }