List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook createSheet
@Override
public XSSFSheet createSheet(String sheetname)
From source file:es.upm.oeg.tools.rdfshapes.utils.CardinalityTemplateGenerator.java
License:Apache License
public static void main(String[] args) throws Exception { OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF, ModelFactory.createDefaultModel()); model.read("http://dublincore.org/2012/06/14/dcelements.ttl"); String endpoint = "http://infra2.dia.fi.upm.es:8899/sparql"; List<String> classList = Files.readAllLines(Paths.get(classListPath), Charset.defaultCharset()); String classPropertyQueryString = readFile(classPropertyQueryPath, Charset.defaultCharset()); String propertyCardinalityQueryString = readFile(propertyCardinalityQueryPath, Charset.defaultCharset()); String individualCountQueryString = readFile(individualCountQueryPath, Charset.defaultCharset()); //Create the Excel workbook and sheet XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet = wb.createSheet("Cardinality"); int currentExcelRow = 0; int classStartRow = 0; for (String clazz : classList) { Map<String, String> litMap = new HashMap<>(); Map<String, String> iriMap = ImmutableMap.of("class", clazz); String queryString = bindQueryString(individualCountQueryString, ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap)); int individualCount; List<RDFNode> c = executeQueryForList(queryString, endpoint, "c"); if (c.size() == 1) { individualCount = c.get(0).asLiteral().getInt(); } else {/*from w w w . j a v a2s.c o m*/ continue; } // If there are zero individuals, continue if (individualCount == 0) { throw new IllegalStateException("Check whether " + classListPath + " and " + endpoint + " match."); } // System.out.println("***"); // System.out.println("### **" + clazz + "** (" + individualCount + ")"); // System.out.println("***"); // System.out.println(); classStartRow = currentExcelRow; XSSFRow row = sheet.createRow(currentExcelRow); XSSFCell cell = row.createCell(0); cell.setCellValue(clazz); cell.getCellStyle().setAlignment(CellStyle.ALIGN_CENTER); queryString = bindQueryString(classPropertyQueryString, ImmutableMap.of(IRI_BINDINGS, iriMap, LITERAL_BINDINGS, litMap)); List<RDFNode> nodeList = executeQueryForList(queryString, endpoint, "p"); for (RDFNode property : nodeList) { if (property.isURIResource()) { String propertyURI = property.asResource().getURI(); // System.out.println("* " + propertyURI); // System.out.println(); XSSFRow propertyRow = sheet.getRow(currentExcelRow); if (propertyRow == null) { propertyRow = sheet.createRow(currentExcelRow); } currentExcelRow++; XSSFCell propertyCell = propertyRow.createCell(1); propertyCell.setCellValue(propertyURI); // System.out.println("| Min Card. |Max Card. |"); // System.out.println("|---|---|"); // System.out.println("| ? | ? |"); // System.out.println(); } } //System.out.println("class start: " + classStartRow + ", class end: " + (currentExcelRow -1)); //We have finished writting properties of one class, now it's time to merge the cells int classEndRow = currentExcelRow - 1; if (classStartRow < classEndRow) { sheet.addMergedRegion(new CellRangeAddress(classStartRow, classEndRow, 0, 0)); } } String filename = "test.xls"; FileOutputStream fileOut = new FileOutputStream(filename); wb.write(fileOut); fileOut.close(); }
From source file:File.XLSX.CreateXLSX.java
public void CreateNew(String data, int Frow, int Fcol, String path, String namafile) { //Blank workbook XSSFWorkbook workbook = new XSSFWorkbook(); //Create a blank sheet XSSFSheet sheet = workbook.createSheet("sheet 1"); int rownum = Frow; String[] split_row = data.split(";"); for (String data_row : split_row) { int cellnum = Fcol; Row row = sheet.createRow(rownum++); String[] split_cols = data_row.split(","); for (String data_cols : split_cols) { Cell cell = row.createCell(cellnum++); cell.setCellValue(data_cols); }/* w w w. ja v a2 s . c o m*/ } try { //Write the workbook in file system File file = new File(path + namafile + ".xlsx"); FileOutputStream out = new FileOutputStream(file); workbook.write(out); out.close(); System.out.println("Berhasil membuat file"); } catch (Exception e) { e.printStackTrace(); } }
From source file:FileHelper.ExcelHelper.java
private void CreateFileResultThread(String fileName) { try {//w ww . j a v a 2 s . c om File excel = new File(fileName); if (excel.exists()) { excel.delete(); } FileOutputStream fos = new FileOutputStream(new File(fileName)); XSSFWorkbook book = new XSSFWorkbook(); XSSFSheet sheet = book.createSheet("sheet1"); book.write(fos); fos.close(); } catch (Exception t) { System.out.println("Throwable CreateFileResultThread " + t.getMessage()); } }
From source file:FileHelper.ExcelHelper.java
private void CreateSheetResult(ThreadResult threadR) { try {/*from ww w. j a v a 2 s. c om*/ File excel = new File("result_threads.xlsx"); FileInputStream fis = new FileInputStream(excel); XSSFWorkbook book = new XSSFWorkbook(fis); XSSFSheet sheet = book.createSheet(threadR.getNameSheet()); // Create Tile Tile Row row = sheet.createRow(0); Cell cell = row.createCell(0); cell.setCellValue("ID"); cell = row.createCell(1); cell.setCellValue("Code Result"); cell = row.createCell(2); cell.setCellValue("Response Time (ms)"); // for (int i = 0; i < threadR.getThreads().size(); i++) { Row row1 = sheet.createRow(i + 1); Cell cell1 = row1.createCell(0); cell1.setCellValue(i + 1); cell1 = row1.createCell(1); cell1.setCellValue(threadR.getThreads().get(i).getCode()); cell1 = row1.createCell(2); cell1.setCellValue(threadR.getThreads().get(i).getTime()); } fis.close(); FileOutputStream fos = new FileOutputStream(new File("result_threads.xlsx")); book.write(fos); fos.close(); } catch (Exception t) { System.out.println("Throwable CreateSheetResult " + t.getMessage()); } }
From source file:fr.paris.lutece.plugins.appointment.service.AppointmentUtilities.java
License:Open Source License
/** * Build the excel fil of the list of the appointments found in the manage appointment viw by filter * //from w w w. j a v a2 s. c o m * @param strIdForm * the form id * @param response * the response * @param locale * the local * @param listAppointmentsDTO * the list of the appointments to input in the excel file * @param stateService * the state service */ public static void buildExcelFileWithAppointments(String strIdForm, HttpServletResponse response, Locale locale, List<AppointmentDTO> listAppointmentsDTO, StateService stateService) { AppointmentFormDTO tmpForm = FormService.buildAppointmentFormLight(Integer.parseInt(strIdForm)); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet(I18nService.getLocalizedString(KEY_RESOURCE_TYPE, locale)); List<Object[]> tmpObj = new ArrayList<Object[]>(); EntryFilter entryFilter = new EntryFilter(); entryFilter.setIdResource(Integer.valueOf(strIdForm)); List<Entry> listEntry = EntryHome.getEntryList(entryFilter); Map<Integer, String> mapDefaultValueGenAttBackOffice = new HashMap<Integer, String>(); for (Entry e : listEntry) { if (e.isOnlyDisplayInBack()) { e = EntryHome.findByPrimaryKey(e.getIdEntry()); if (e.getFields() != null && e.getFields().size() == 1 && !StringUtils.isEmpty(e.getFields().get(0).getValue())) { mapDefaultValueGenAttBackOffice.put(e.getIdEntry(), e.getFields().get(0).getValue()); } else if (e.getFields() != null) { for (Field field : e.getFields()) { if (field.isDefaultValue()) { mapDefaultValueGenAttBackOffice.put(e.getIdEntry(), field.getValue()); } } } } } int nTaille = 10 + (listEntry.size() + 1); if (tmpForm != null) { int nIndex = 0; Object[] strWriter = new String[1]; strWriter[0] = tmpForm.getTitle(); tmpObj.add(strWriter); Object[] strInfos = new String[nTaille]; strInfos[0] = I18nService.getLocalizedString(KEY_COLUMN_LAST_NAME, locale); strInfos[1] = I18nService.getLocalizedString(KEY_COLUMN_FISRT_NAME, locale); strInfos[2] = I18nService.getLocalizedString(KEY_COLUMN_EMAIL, locale); strInfos[3] = I18nService.getLocalizedString(KEY_COLUMN_DATE_APPOINTMENT, locale); strInfos[4] = I18nService.getLocalizedString(KEY_TIME_START, locale); strInfos[5] = I18nService.getLocalizedString(KEY_TIME_END, locale); strInfos[6] = I18nService.getLocalizedString(KEY_COLUMN_ADMIN, locale); strInfos[7] = I18nService.getLocalizedString(KEY_COLUMN_STATUS, locale); strInfos[8] = I18nService.getLocalizedString(KEY_COLUMN_STATE, locale); strInfos[9] = I18nService.getLocalizedString(KEY_COLUMN_NB_BOOKED_SEATS, locale); nIndex = 1; if (listEntry.size() > 0) { for (Entry e : listEntry) { strInfos[10 + nIndex] = e.getTitle(); nIndex++; } } tmpObj.add(strInfos); } if (listAppointmentsDTO != null) { for (AppointmentDTO appointmentDTO : listAppointmentsDTO) { int nIndex = 0; Object[] strWriter = new String[nTaille]; strWriter[0] = appointmentDTO.getLastName(); strWriter[1] = appointmentDTO.getFirstName(); strWriter[2] = appointmentDTO.getEmail(); strWriter[3] = appointmentDTO.getDateOfTheAppointment(); strWriter[4] = appointmentDTO.getStartingTime().toString(); strWriter[5] = appointmentDTO.getEndingTime().toString(); strWriter[6] = appointmentDTO.getAdminUser(); String status = I18nService.getLocalizedString(AppointmentDTO.PROPERTY_APPOINTMENT_STATUS_RESERVED, locale); if (appointmentDTO.getIsCancelled()) { status = I18nService.getLocalizedString(AppointmentDTO.PROPERTY_APPOINTMENT_STATUS_UNRESERVED, locale); } strWriter[7] = status; State stateAppointment = stateService.findByResource(appointmentDTO.getIdAppointment(), Appointment.APPOINTMENT_RESOURCE_TYPE, tmpForm.getIdWorkflow()); String strState = StringUtils.EMPTY; if (stateAppointment != null) { appointmentDTO.setState(stateAppointment); strState = stateAppointment.getName(); } strWriter[8] = strState; nIndex = 1; strWriter[9] = Integer.toString(appointmentDTO.getNbBookedSeats()); List<Integer> listIdResponse = AppointmentResponseService .findListIdResponse(appointmentDTO.getIdAppointment()); List<Response> listResponses = new ArrayList<Response>(); for (int nIdResponse : listIdResponse) { Response resp = ResponseHome.findByPrimaryKey(nIdResponse); if (resp != null) { listResponses.add(resp); } } for (Entry e : listEntry) { Integer key = e.getIdEntry(); StringBuffer strValue = new StringBuffer(StringUtils.EMPTY); String strPrefix = StringUtils.EMPTY; for (Response resp : listResponses) { String strRes = StringUtils.EMPTY; if (key.equals(resp.getEntry().getIdEntry())) { Field f = resp.getField(); int nfield = 0; if (f != null) { nfield = f.getIdField(); Field field = FieldHome.findByPrimaryKey(nfield); if (field != null) { strRes = field.getTitle(); } } else { strRes = resp.getResponseValue(); } } if ((strRes != null) && !strRes.isEmpty()) { strValue.append(strPrefix + strRes); strPrefix = CONSTANT_COMMA; } } if (strValue.toString().isEmpty() && mapDefaultValueGenAttBackOffice.containsKey(key)) { strValue.append(mapDefaultValueGenAttBackOffice.get(key)); } if (!strValue.toString().isEmpty()) { strWriter[10 + nIndex] = strValue.toString(); } nIndex++; } tmpObj.add(strWriter); } } int nRownum = 0; for (Object[] myObj : tmpObj) { Row row = sheet.createRow(nRownum++); int nCellnum = 0; for (Object strLine : myObj) { Cell cell = row.createCell(nCellnum++); if (strLine instanceof String) { cell.setCellValue((String) strLine); } else if (strLine instanceof Boolean) { cell.setCellValue((Boolean) strLine); } else if (strLine instanceof Date) { cell.setCellValue((Date) strLine); } else if (strLine instanceof Double) { cell.setCellValue((Double) strLine); } } } try { String now = new SimpleDateFormat("yyyyMMdd-hhmm") .format(GregorianCalendar.getInstance(locale).getTime()) + "_" + I18nService.getLocalizedString(KEY_RESOURCE_TYPE, locale) + EXCEL_FILE_EXTENSION; response.setContentType(EXCEL_MIME_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + now + "\";"); response.setHeader("Pragma", "public"); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate,post-check=0,pre-check=0"); OutputStream os = response.getOutputStream(); workbook.write(os); os.close(); workbook.close(); } catch (IOException e) { AppLogService.error(e); } }
From source file:GapAnalysis.gapAnalysis.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); //PrintWriter out = response.getWriter(); try {//from w w w. j a v a2s. c om ArrayList keyal = new ArrayList(); ArrayList countyal = new ArrayList(); ArrayList scountyal = new ArrayList(); ArrayList facilal = new ArrayList(); ArrayList yearmonthal = new ArrayList(); ArrayList monthal = new ArrayList(); ArrayList sectional = new ArrayList(); XSSFWorkbook wb; String periodname = ""; String allpath = getServletContext().getRealPath("/Gapanalysis.xlsm"); System.out.println(allpath); XSSFWorkbook workbook; String mydrive = allpath.substring(0, 1); // wb = new XSSFWorkbook( OPCPackage.open(allpath) ); Date da = new Date(); String dat2 = da.toString().replace(" ", "_"); dat2 = dat2.toString().replace(":", "_"); String np = mydrive + ":\\APHIAPLUS\\InternalSystem\\Gapanalysis" + dat2 + ".xlsm"; System.out.println("path:: " + np); // String desteepath1 = getServletContext().getRealPath("/Females 15to24.xlsm"); String sr = getServletContext().getRealPath("/Gapanalysis.xlsm"); //check if file exists //first time , it should create those folders that host the macro file File f = new File(np); if (!f.exists() && !f.isDirectory()) { /* do something */ copytemplates ct = new copytemplates(); ct.transfermacros(sr, np); //rem np is the destination file name System.out.println("Copying macro template first time .."); } else //copy the file alone { copytemplates ct = new copytemplates(); //copy the agebased file only ct.copymacros(sr, np); } String filepth = np; File allpathfile = new File(filepth); OPCPackage pkg = OPCPackage.open(allpathfile); pathtodelete = filepth; wb = new XSSFWorkbook(pkg); dbConn conn = new dbConn(); HashMap<String, String> rawdatahashmap = new HashMap<String, String>(); int year = 0; String yearval = ""; int prevyear = 0; String quarter = ""; String yearmonth = ""; String startyearmonth = ""; String endyearmonth = ""; yearval = request.getParameter("year").toString(); System.out.println("YEARVAL" + yearval); year = Integer.parseInt(yearval); prevyear = year - 1; quarter = request.getParameter("quarter"); periodname += yearval + "_"; if (quarter.equals("1")) { startyearmonth = prevyear + "10"; endyearmonth = prevyear + "12"; periodname = prevyear + "_(Oct_Dec)"; } else if (quarter.equals("2")) { startyearmonth = year + "01"; endyearmonth = year + "03"; periodname = yearval + "_(Jan-Mar)"; } else if (quarter.equals("3")) { startyearmonth = year + "04"; endyearmonth = year + "06"; periodname = yearval + "_(Apr_Jun)"; } else if (quarter.equals("4")) { startyearmonth = year + "07"; endyearmonth = year + "09"; periodname = yearval + "_(Jul_Sep)"; } int colsmerging = 6; String Sections[] = { "ART", "HTC", "PMTCT" }; String headers[] = { "County", "Sub-County", "Facility", "Year", "Month" }; String headergsn[] = { "County", "Sub-County", "Facility" }; //if one wants gaps for one service area if (request.getParameterValues("gapsection") != null) { Sections = request.getParameterValues("gapsection"); } //This is the loop that well use to create worksheets for each String period = " 1=1 and Annee=" + yearval + " and yearmonth between " + startyearmonth + " and " + endyearmonth + " "; String gsnperiod = " 1=1 "; //______________________________________________________________________________________ //______________________________________________________________________________________ Font font = wb.createFont(); font.setFontHeightInPoints((short) 18); font.setFontName("Cambria"); font.setColor((short) 0000); CellStyle style = wb.createCellStyle(); style.setFont(font); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); Font font2 = wb.createFont(); font2.setFontName("Cambria"); font2.setColor((short) 0000); CellStyle style2 = wb.createCellStyle(); style2.setFont(font2); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_LEFT); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); CellStyle stborder = wb.createCellStyle(); stborder.setBorderTop(HSSFCellStyle.BORDER_THIN); stborder.setBorderBottom(HSSFCellStyle.BORDER_THIN); stborder.setBorderLeft(HSSFCellStyle.BORDER_THIN); stborder.setBorderRight(HSSFCellStyle.BORDER_THIN); stborder.setAlignment(HSSFCellStyle.ALIGN_CENTER); CellStyle stylex = wb.createCellStyle(); stylex.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); stylex.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); stylex.setBorderTop(HSSFCellStyle.BORDER_THIN); stylex.setBorderBottom(HSSFCellStyle.BORDER_THIN); stylex.setBorderLeft(HSSFCellStyle.BORDER_THIN); stylex.setBorderRight(HSSFCellStyle.BORDER_THIN); stylex.setAlignment(HSSFCellStyle.ALIGN_CENTER); CellStyle stylex1 = wb.createCellStyle(); stylex1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); stylex1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); stylex1.setBorderTop(HSSFCellStyle.BORDER_THIN); stylex1.setBorderBottom(HSSFCellStyle.BORDER_THIN); stylex1.setBorderLeft(HSSFCellStyle.BORDER_THIN); stylex1.setBorderRight(HSSFCellStyle.BORDER_THIN); stylex1.setAlignment(HSSFCellStyle.ALIGN_LEFT); CellStyle stylex2 = wb.createCellStyle(); stylex2.setFillForegroundColor(HSSFColor.SKY_BLUE.index); stylex2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); stylex2.setBorderTop(HSSFCellStyle.BORDER_THIN); stylex2.setBorderBottom(HSSFCellStyle.BORDER_THIN); stylex2.setBorderLeft(HSSFCellStyle.BORDER_THIN); stylex2.setBorderRight(HSSFCellStyle.BORDER_THIN); stylex2.setAlignment(HSSFCellStyle.ALIGN_CENTER); CellStyle stylex3 = wb.createCellStyle(); stylex3.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); stylex3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); stylex3.setBorderTop(HSSFCellStyle.BORDER_THIN); stylex3.setBorderBottom(HSSFCellStyle.BORDER_THIN); stylex3.setBorderLeft(HSSFCellStyle.BORDER_THIN); stylex3.setBorderRight(HSSFCellStyle.BORDER_THIN); stylex3.setAlignment(HSSFCellStyle.ALIGN_CENTER); Font fontx = wb.createFont(); fontx.setColor(HSSFColor.BLACK.index); fontx.setFontName("Cambria"); stylex.setFont(fontx); stylex.setWrapText(true); stylex1.setFont(fontx); stylex1.setWrapText(true); stylex2.setFont(fontx); stylex2.setWrapText(true); //================================================== for (int a = 0; a < Sections.length; a++) { int column = 0; int Row = 3; Sheet shet = wb.createSheet(Sections[a]); Row rwx = shet.createRow(2); Row rw1 = null; Row rw2 = null; Row rw = shet.createRow(0); rw.setHeightInPoints(25); Cell cl0 = rw.createCell(0); cl0.setCellValue(Sections[a] + " GAP ANALYSIS"); cl0.setCellStyle(stylex1); //this will depend on the length of the number of elements being checked for (int b = 1; b <= colsmerging; b++) { Cell clx = rw.createCell(b); clx.setCellValue(""); clx.setCellStyle(stylex); } //now go to the database and do a query for each section int determinant = 2; String getqueries = " Select * from gap_analysis where active=1 and section='" + Sections[a] + "' "; conn.rs = conn.st.executeQuery(getqueries); while (conn.rs.next()) { //if an excel sheet exists, then get the row number 1 if (shet.getRow(1) != null) { rw1 = shet.getRow(1); } else { rw1 = shet.createRow(1); rw1.setHeightInPoints(25); } //print blanks before printing real header //for gsns, we only print three columns and no period if (conn.rs.getString("id").equals("1")) { for (int p = 0; p < headergsn.length; p++) { Cell cl2 = rw1.createCell(column + p); cl2.setCellValue(""); cl2.setCellStyle(stylex); shet.setColumnWidth(column + p, 5000); } } else { for (int p = 0; p < headers.length; p++) { Cell cl2 = rw1.createCell(column + p); cl2.setCellValue(""); cl2.setCellStyle(stylex); shet.setColumnWidth(column + p, 5000); } } determinant++; if (determinant % 2 == 0) { Cell cl1 = rw1.createCell(column); cl1.setCellValue(conn.rs.getString("rule")); cl1.setCellStyle(stylex3); } else { Cell cl1 = rw1.createCell(column); cl1.setCellValue(conn.rs.getString("rule")); cl1.setCellStyle(stylex2); } //Create the column header if (shet.getRow(2) != null) { rw2 = shet.getRow(2); } else { rw2 = shet.createRow(2); rw2.setHeightInPoints(25); } if (conn.rs.getString("id").equals("1")) { for (int p = 0; p < headergsn.length; p++) { Cell cl2 = rw2.createCell(column + p); cl2.setCellValue(headergsn[p]); cl2.setCellStyle(stylex); } } else { for (int p = 0; p < headers.length; p++) { Cell cl2 = rw2.createCell(column + p); cl2.setCellValue(headers[p]); cl2.setCellStyle(stylex); } } String currentqry = conn.rs.getString("query"); //process each query as you //pass the necessary period parameters from the interface //rem each query ends with a 'and' if (conn.rs.getString("id").equals("1")) { currentqry += gsnperiod; } else { currentqry += period + " and subpartnera." + Sections[a] + "= 1 "; } System.out.println("" + currentqry); Row = 3; conn.rs1 = conn.st1.executeQuery(currentqry); while (conn.rs1.next()) { if (shet.getRow(Row) != null) { rwx = shet.getRow(Row); } else { rwx = shet.createRow(Row); rwx.setHeightInPoints(25); } Cell cly = rwx.createCell(column); cly.setCellValue(conn.rs1.getString("County")); cly.setCellStyle(style2); Cell cly2 = rwx.createCell(column + 1); cly2.setCellValue(conn.rs1.getString("DistrictNom")); cly2.setCellStyle(style2);//gsn sites do not have a yearmonth Cell cly1 = rwx.createCell(column + 2); cly1.setCellValue(conn.rs1.getString("SubPartnerNom")); cly1.setCellStyle(style2); //if the current list is not inclusive of GSNs if (!conn.rs.getString(1).equals("1")) { Cell cly3 = rwx.createCell(column + 3); cly3.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(0, 4))); cly3.setCellStyle(style2); //the month section Cell cly3x = rwx.createCell(column + 4); cly3x.setCellValue(new Integer(conn.rs1.getString("yearmonth").substring(4))); cly3x.setCellStyle(style2); //my key is a String mykey = Sections[a] + conn.rs1.getString("SubPartnerNom") + "_" + conn.rs1.getString("yearmonth") + "_"; //add all the facilities at this point //ignore the sites in ART since they are static if (!keyal.contains(mykey)) { keyal.add(mykey); countyal.add(conn.rs1.getString("County")); scountyal.add(conn.rs1.getString("DistrictNom")); facilal.add(conn.rs1.getString("SubPartnerNom")); sectional.add(Sections[a]); yearmonthal.add(conn.rs1.getString("yearmonth")); monthal.add(conn.rs1.getString("yearmonth").substring(4)); } } Row++; } if (conn.rs.getString(1).equals("1")) { column += 3; } else { column += 5; } if (conn.rs.getString("id").equals("1")) { shet.addMergedRegion(new CellRangeAddress(1, 1, 0, column - 1)); } else { shet.addMergedRegion(new CellRangeAddress(1, 1, column - 5, column - 1)); } } //end of all queries per section shet.addMergedRegion(new CellRangeAddress(0, 0, 0, column - 1)); } // end of sheets loop //create a new sheet //county subcounty facility yearmonth section Sheet shet = wb.getSheet("Sheet1"); Row rw = shet.createRow(0); Cell cl0 = rw.createCell(0); cl0.setCellValue("county"); cl0.setCellStyle(stylex1); Cell cl1 = rw.createCell(1); cl1.setCellValue("subcounty"); cl1.setCellStyle(stylex1); Cell cl2 = rw.createCell(2); cl2.setCellValue("facility"); cl2.setCellStyle(stylex1); Cell cl3 = rw.createCell(3); cl3.setCellValue("year"); cl3.setCellStyle(stylex1); Cell cl4 = rw.createCell(4); cl4.setCellValue("month"); cl4.setCellStyle(stylex1); Cell cl5 = rw.createCell(5); cl5.setCellValue("section"); cl5.setCellStyle(stylex1); for (int q = 0; q < keyal.size(); q++) { Row rwx = shet.createRow(q + 1); Cell cl01 = rwx.createCell(0); cl01.setCellValue(countyal.get(q).toString()); cl01.setCellStyle(style2); Cell cl11 = rwx.createCell(1); cl11.setCellValue(scountyal.get(q).toString()); cl11.setCellStyle(style2); Cell cl21 = rwx.createCell(2); cl21.setCellValue(facilal.get(q).toString()); cl21.setCellStyle(style2); Cell cl31 = rwx.createCell(3); cl31.setCellValue(new Integer(yearmonthal.get(q).toString().substring(0, 4))); cl31.setCellStyle(style2); Cell cl41 = rwx.createCell(4); cl41.setCellValue(new Integer(monthal.get(q).toString())); cl41.setCellStyle(style2); Cell cl51 = rwx.createCell(5); cl51.setCellValue(sectional.get(q).toString()); cl51.setCellStyle(style2); } IdGenerator IG = new IdGenerator(); String createdOn = IG.CreatedOn(); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); wb.write(outByteStream); byte[] outArray = outByteStream.toByteArray(); response.setContentType("application/ms-excel"); response.setContentLength(outArray.length); response.setHeader("Expires:", "0"); // eliminates browser caching response.setHeader("Content-Disposition", "attachment; filename=GapAnalysis_For" + periodname + "_Generatted_On_" + createdOn + ".xlsm"); OutputStream outStream = response.getOutputStream(); outStream.write(outArray); outStream.flush(); outStream.close(); pkg.close(); if (conn.rs != null) { conn.rs.close(); } if (conn.rs1 != null) { conn.rs1.close(); } if (conn.st1 != null) { conn.st1.close(); } if (conn.st != null) { conn.st.close(); } File file = new File(pathtodelete); System.out.println("path: 2" + pathtodelete); if (file.delete()) { System.out.println(file.getName() + " is deleted!"); } else { System.out.println("Delete operation failed."); } } catch (SQLException ex) { Logger.getLogger(gapAnalysis.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidFormatException ex) { Logger.getLogger(gapAnalysis.class.getName()).log(Level.SEVERE, null, ex); } finally { } }
From source file:gov.anl.cue.arcane.engine.matrix.MatrixEngine.java
License:Open Source License
/** * Write engine file.//from w ww. ja v a 2 s.c om * * @param fileName the file name * @return true, if successful */ public boolean writeEngineFile(String fileName) { // Check for errors. try { // Create the requested workbook image. XSSFWorkbook workbook = new XSSFWorkbook(); // Create the parameters sheet. XSSFSheet sheet = workbook.createSheet("Parameters"); // Create the rows. this.createRowHeader(workbook, sheet, 0, "Parameter", "Value"); this.createRowInt(sheet, 1, "Random Seed", this.randomSeed); this.createRowInt(sheet, 2, "Population Size", this.populationSize); this.createRowDouble(sheet, 3, "Kill Fraction", this.killFraction); this.createRowDouble(sheet, 4, "Crossover Probability", this.crossoverProbability); this.createRowDouble(sheet, 5, "Mutation Probability for Cells", this.mutationProbabilityForCells); // Attempt to create the requested file from the workbook image. FileOutputStream file = new FileOutputStream(fileName); workbook.write(file); file.close(); // Catch errors. } catch (Exception e) { // Note the error. return false; } // Return the default results. return true; }
From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java
License:Open Source License
/** * Write scan variables./*from ww w . j av a 2 s .co m*/ * * @param workbook the workbook * @param cellStyle the cell style * @throws OutOfRangeException the out of range exception */ public void writeScanVariables(XSSFWorkbook workbook, XSSFCellStyle cellStyle) throws OutOfRangeException { // Scan the variables. for (MatrixVariable matrixVariable : this) { // Fill in a header. XSSFSheet sheet = workbook .createSheet(matrixVariable.name + " (" + matrixVariable.units.getUnit() + ")"); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue("Equation"); cell.setCellStyle(cellStyle); cell = row.createCell(1); cell.setCellValue("Node"); cell.setCellStyle(cellStyle); for (int rowIndex = 0; rowIndex < matrixVariable.equations.size(); rowIndex++) { cell = row.createCell(rowIndex + 2); cell.setCellValue(this.nodeName(rowIndex)); cell.setCellStyle(cellStyle); } // Fill in the main rows. for (int rowIndex = 0; rowIndex < matrixVariable.equations.size(); rowIndex++) { // Create the next row. row = sheet.createRow(rowIndex + 1); // Create the equation column. cell = row.createCell(0); cell.setCellValue(matrixVariable.equations.get(rowIndex)); // Create the node index column. cell = row.createCell(1); cell.setCellValue(this.nodeName(rowIndex)); cell.setCellStyle(cellStyle); // Fill in the coefficients. for (int columnIndex = 0; columnIndex < matrixVariable.equations.size(); columnIndex++) { cell = row.createCell(columnIndex + 2); double cellValue = matrixVariable.coefficients.getEntry(rowIndex, columnIndex); if (!Double.isNaN(cellValue)) { cell.setCellValue(cellValue); } } } } }
From source file:gov.anl.cue.arcane.engine.matrix.MatrixModel.java
License:Open Source License
/** * Write fitness function information.//from w w w. j a va 2 s . co m * * @param workbook the workbook * @param cellStyle the cell style * @return the XSSF sheet */ public XSSFSheet writeFitnessFunctionInformation(XSSFWorkbook workbook, XSSFCellStyle cellStyle) { // Fill in the fitness header. XSSFSheet sheet = workbook.createSheet("Fitness"); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue("Equation"); cell.setCellStyle(cellStyle); cell = row.createCell(1); cell.setCellValue("Node"); cell.setCellStyle(cellStyle); // Fill in the fitness equations. for (int rowIndex = 0; rowIndex < fitnessEquations.size(); rowIndex++) { // Create the next row. row = sheet.createRow(rowIndex + 1); // Create the equation column. cell = row.createCell(0); cell.setCellValue(this.fitnessEquations.get(rowIndex)); // Create the node index column. cell = row.createCell(1); cell.setCellValue(this.nodeName(rowIndex)); cell.setCellStyle(cellStyle); } // Fill in the fitness value footer. row = sheet.createRow(fitnessEquations.size() + 1); cell = row.createCell(0); if (this.fitnessFunctionType == MatrixModel.FITNESS_FUNCTION_TYPE.SIMPLE_MAXIMUM) { cell.setCellValue(MatrixModel.SIMPLE_MAXIMUM_STRING); } else if (this.fitnessFunctionType == MatrixModel.FITNESS_FUNCTION_TYPE.USER_EQUATION) { cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_STRING); } else { cell.setCellValue(MatrixModel.ZERO_FITNESS_STRING); } cell = row.createCell(1); if (!Double.isNaN(this.getFitnessValue())) { cell.setCellValue(this.getFitnessValue()); } // Fill in the step count and size. if (this.fitnessFunctionType == MatrixModel.FITNESS_FUNCTION_TYPE.USER_EQUATION) { row = sheet.createRow(fitnessEquations.size() + 2); cell = row.createCell(0); cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_STEP_COUNT_STRING); cell = row.createCell(1); cell.setCellValue(this.stepCount); row = sheet.createRow(fitnessEquations.size() + 3); cell = row.createCell(0); cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_STEP_SIZE_STRING); cell = row.createCell(1); cell.setCellValue(this.stepSize); row = sheet.createRow(fitnessEquations.size() + 4); cell = row.createCell(0); cell.setCellValue(MatrixModel.SYSTEM_DYNAMICS_GROW_STRING); cell = row.createCell(1); if (this.equationEvolution) { cell.setCellValue("Yes"); } else { cell.setCellValue("No"); } } // Return the results. return sheet; }
From source file:gov.nih.nci.evs.app.neopl.CSVtoExcel.java
License:Open Source License
public void runXSSF(String inputfile) { int size = checkSpecialCharacters(inputfile); int n = inputfile.lastIndexOf("."); //String outputfile = inputfile.substring(0, n) + ".xlsx"; String outputfile = getOutputFile(inputfile, ".xlsx"); try {/*from w w w . ja v a2 s. c o m*/ XSSFWorkbook wb = new XSSFWorkbook(); XSSFCreationHelper helper = null; XSSFCellStyle cellStyle = wb.createCellStyle(); XSSFFont font = wb.createFont(); font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); cellStyle.setFont(font); XSSFCellStyle linkCellStyle = wb.createCellStyle(); XSSFFont linkfont = wb.createFont(); //XSSFColor color = new XSSFColor(Color.LIGHT_BLUE); XSSFColor color = new XSSFColor(Color.BLUE); linkfont.setColor(color); //linkfont.setColor(XSSFColor.LIGHT_BLUE.index); linkCellStyle.setFont(linkfont); CSVReader reader = new CSVReader(new FileReader(inputfile));//CSV file String[] line; int r = 0; Cell cell = null; XSSFHyperlink url_link = null; XSSFSheet sheet = null; int page_num = 1; Row row = null; int lcv = 0; int row_count = 0; try { while ((line = reader.readNext()) != null) { if (lcv % PAGE_SIZE == 0) { r = 0; String sheetLabel = SHEET_LABEL; if (size > PAGE_SIZE) { sheetLabel = sheetLabel + " (Page " + page_num + ")"; } //System.out.println("Creating " + sheetLabel); sheet = wb.createSheet(sheetLabel); helper = sheet.getWorkbook().getCreationHelper(); url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL); row = sheet.createRow((short) r); for (int i = 0; i < HEADINGS.length; i++) { String heading = HEADINGS[i]; cell = row.createCell(i); cell.setCellValue(heading); cell.setCellStyle(cellStyle); } page_num++; } else { String s4 = (String) line[4]; s4 = s4.trim(); r++; row = sheet.createRow((short) r); row_count++; cell = row.createCell(0); String ncit_code = line[0]; cell.setCellValue(ncit_code); if (NCIT_LINK) { url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL); url_link.setAddress(getNCItHyperlink(ncit_code)); cell.setHyperlink(url_link); cell.setCellStyle(linkCellStyle); } cell = row.createCell(1); String name = line[1]; cell.setCellValue(line[1]); cell = row.createCell(2); cell.setCellValue(line[2]); if (NCIM_LINK) { String s2 = line[2]; s2 = s2.trim(); if (s2.length() > 0) { url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL); url_link.setAddress(getNCImHyperlink(s2)); cell.setHyperlink(url_link); cell.setCellStyle(linkCellStyle); } } cell = row.createCell(3); String ncim_name = line[3]; cell.setCellValue(line[3]); cell = row.createCell(4); cell.setCellValue(line[4]); cell = row.createCell(5); String atom_name = (String) line[5]; cell.setCellValue(line[5]); cell = row.createCell(6); cell.setCellValue(line[6]); if (SOURCE_LINK) { if (s4.length() > 0) { String s6 = (String) line[6]; if (localNameMap.containsKey(s4)) { url_link = helper.createHyperlink(XSSFHyperlink.LINK_URL); s4 = (String) localNameMap.get(s4); url_link.setAddress(getSourceHyperlink(s4, s6)); cell.setHyperlink(url_link); cell.setCellStyle(linkCellStyle); } } } cell = row.createCell(7); cell.setCellValue(line[7]); } lcv++; } } catch (Exception ex) { ex.printStackTrace(); } // Write the output to a file FileOutputStream fileOut = new FileOutputStream(outputfile); wb.write(fileOut); fileOut.close(); System.out.println("Output file " + outputfile + " generated."); System.out.println("row_count: " + row_count); } catch (Exception ex) { ex.printStackTrace(); } }