List of usage examples for org.apache.poi.ss.usermodel Workbook getCreationHelper
CreationHelper getCreationHelper();
From source file:com.mycompany.mavenproject1.ragaiproject.PDFManipulation.java
public void convert(List<PDDocument> pdfList, List<String> selectedFields, String fileName) { Workbook wb = new HSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); HSSFSheet s1 = (HSSFSheet) wb.createSheet("Sheet 1"); Row header = s1.createRow((short) 0); //initialize column headers for (int i = 0; i < selectedFields.size(); i++) { Cell headerCell = header.createCell(i); headerCell.setCellValue(selectedFields.get(i)); }/*w ww.ja v a2 s. c o m*/ //for(int i = 0; i < selectedFields.size();i++){ //fills out row //Cell dataCell = data.createCell(i); for (int y = 0; y < pdfList.size(); y++) { PDDocumentCatalog docCatalog = pdfList.get(y).getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); java.util.List<PDField> fields = acroForm.getFields(); Row data = s1.createRow((short) y + 1); for (int i = 0; i < selectedFields.size(); i++) { Cell dataCell = data.createCell(i); for (PDField field : fields) { System.out.println("Field Value: " + field.getValueAsString()); if (field.getPartialName().equals(selectedFields.get(i))) { dataCell.setCellValue(field.getValueAsString()); } } } /* for(int j = 0; j < this.fieldLabelPairs.size();j++){ if(this.fieldLabelPairs.get(j).getLabel().equals(selectedFields.get(i))){ dataCell.setCellValue(this.fieldLabelPairs.get(j).getValue()); } }*/ } //} /*for (int i = 0; i < selectedFields.size(); i++){ Row data = s1.createRow(i+1); for(int j = 0; j< this.fieldLabelPairs.length; j++){ Cell dataCell = data.createCell(i); if(this.fieldLabelPairs[j].getLabel().equals(selectedFields.get(i))){ dataCell.setCellValue(this.fieldLabelPairs[j].getValue()); } } }*/ FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(fileName + ".xls"); try { wb.write(fileOut); fileOut.close(); } catch (IOException ex) { Logger.getLogger(ExcelExport.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { Logger.getLogger(ExcelExport.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.openitech.db.model.ExcelDataSource.java
License:Apache License
@Override public boolean loadData(boolean reload, int oldRow) { boolean result = false; if (isDataLoaded && !reload) { return false; }/*from www .java 2s. c o m*/ if (sourceFile != null) { try { Workbook workBook = WorkbookFactory.create(new FileInputStream(sourceFile)); // HSSFWorkbook workBook = new HSSFWorkbook(new FileInputStream(sourceFile)); Sheet sheet = workBook.getSheetAt(0); DataFormatter dataFormatter = new DataFormatter(Locale.GERMANY); FormulaEvaluator formulaEvaluator = workBook.getCreationHelper().createFormulaEvaluator(); int lastRowNum = sheet.getLastRowNum(); boolean isFirstLineHeader = true; //count = sheet. - (isFirstLineHeader ? 1 : 0); int tempCount = 0; for (int j = 0; j <= lastRowNum; j++) { //zane se z 0 Row row = row = sheet.getRow(j); if (row == null) { continue; } // display row number in the console. System.out.println("Row No.: " + row.getRowNum()); if (isFirstLineHeader && row.getRowNum() == 0) { populateHeaders(row); continue; } tempCount++; Map<String, DataColumn> values; if (rowValues.containsKey(row.getRowNum())) { values = rowValues.get(row.getRowNum()); } else { values = new HashMap<String, DataColumn>(); rowValues.put(row.getRowNum(), values); } // once get a row its time to iterate through cells. int lastCellNum = row.getLastCellNum(); for (int i = 0; i <= lastCellNum; i++) { DataColumn dataColumn = new DataColumn(); Cell cell = row.getCell(i); if (cell == null) { continue; } System.out.println("Cell No.: " + cell.getColumnIndex()); System.out.println("Value: " + dataFormatter.formatCellValue(cell)); if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { dataColumn = new DataColumn(dataFormatter.formatCellValue(cell, formulaEvaluator)); } else { dataColumn = new DataColumn(dataFormatter.formatCellValue(cell)); } switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: { // cell type numeric. System.out.println("Numeric value: " + cell.getNumericCellValue()); dataColumn = new DataColumn(dataFormatter.formatCellValue(cell)); break; } case Cell.CELL_TYPE_STRING: // cell type string. System.out.println("String value: " + cell.getStringCellValue()); dataColumn = new DataColumn(dataFormatter.formatCellValue(cell)); break; case Cell.CELL_TYPE_BOOLEAN: // cell type string. System.out.println("String value: " + cell.getBooleanCellValue()); dataColumn.setValue(cell.getBooleanCellValue(), Boolean.class); break; case Cell.CELL_TYPE_FORMULA: // cell type string. System.out.println( "Formula value: " + dataFormatter.formatCellValue(cell, formulaEvaluator)); dataColumn = new DataColumn(dataFormatter.formatCellValue(cell, formulaEvaluator)); break; default: dataColumn.setValue(cell.getStringCellValue(), String.class); break; } values.put(getColumnName(cell.getColumnIndex()).toUpperCase(), dataColumn); } } count = tempCount; isDataLoaded = true; //se postavim na staro vrstico ali 1 if (oldRow > 0) { absolute(oldRow); } else { first(); } result = true; } catch (Exception ex) { Logger.getLogger(ExcelDataSource.class.getName()).log(Level.SEVERE, null, ex); result = false; } } return result; }
From source file:com.quanticate.opensource.datalistdownload.DeclarativeSpreadsheetWebScript.java
License:Open Source License
/** * Generates the spreadsheet, based on the properties in the header * and a callback for the body./* w w w . j av a 2 s . c om*/ */ public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status, Map<String, Object> model) throws IOException { Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)"); // Build up the details of the header List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req); String[] headings = new String[propertyDetails.size()]; String[] descriptions = new String[propertyDetails.size()]; boolean[] required = new boolean[propertyDetails.size()]; for (int i = 0; i < headings.length; i++) { Pair<QName, Boolean> property = propertyDetails.get(i); if (property == null || property.getFirst() == null) { headings[i] = ""; required[i] = false; } else { QName column = property.getFirst(); required[i] = property.getSecond(); // Ask the dictionary service nicely for the details PropertyDefinition pd = dictionaryService.getProperty(column); if (pd != null && pd.getTitle(dictionaryService) != null) { // Use the friendly titles, which may even be localised! headings[i] = pd.getTitle(dictionaryService); descriptions[i] = pd.getDescription(dictionaryService); } else { // Nothing friendly found, try to munge the raw qname into // something we can show to a user... String raw = column.getLocalName(); raw = raw.substring(0, 1).toUpperCase() + raw.substring(1); Matcher m = qnameMunger.matcher(raw); if (m.matches()) { headings[i] = m.group(1) + " " + m.group(2); } else { headings[i] = raw; } } } } // Build a list of just the properties List<QName> properties = new ArrayList<QName>(propertyDetails.size()); for (Pair<QName, Boolean> p : propertyDetails) { QName qn = null; if (p != null) { qn = p.getFirst(); } properties.add(qn); } // Output if ("csv".equals(format)) { StringWriter sw = new StringWriter(); CSVPrinter csv = new CSVPrinter(sw, CSVStrategy.EXCEL_STRATEGY); csv.println(headings); populateBody(resource, csv, properties); model.put(MODEL_CSV, sw.toString()); } else if ("odf".equals(format) || "ods".equals(format)) { try { SpreadsheetDocument odf = SpreadsheetDocument.newSpreadsheetDocument(); // Add the header row Table sheet = odf.appendSheet("Export"); org.odftoolkit.simple.table.Row hr = sheet.appendRow(); // TODO // Have the contents populated // TODO // Save it for the template ByteArrayOutputStream baos = new ByteArrayOutputStream(); odf.save(baos); model.put(MODEL_ODF, baos.toByteArray()); } catch (Exception e) { throw new WebScriptException("Error creating ODF file", e); } } else { Workbook wb; if ("xlsx".equals(format)) { wb = new XSSFWorkbook(); // TODO Properties } else { wb = new HSSFWorkbook(); // TODO Properties } // Add our header row Sheet sheet = wb.createSheet("Export"); Row hr = sheet.createRow(0); sheet.createFreezePane(0, 1); Font fb = wb.createFont(); fb.setBoldweight(Font.BOLDWEIGHT_BOLD); Font fi = wb.createFont(); fi.setBoldweight(Font.BOLDWEIGHT_BOLD); fi.setItalic(true); CellStyle csReq = wb.createCellStyle(); csReq.setFont(fb); CellStyle csOpt = wb.createCellStyle(); csOpt.setFont(fi); // Populate the header Drawing draw = null; for (int i = 0; i < headings.length; i++) { Cell c = hr.createCell(i); c.setCellValue(headings[i]); if (required[i]) { c.setCellStyle(csReq); } else { c.setCellStyle(csOpt); } if (headings[i].length() == 0) { sheet.setColumnWidth(i, 3 * 250); } else { sheet.setColumnWidth(i, 18 * 250); } if (descriptions[i] != null && descriptions[i].length() > 0) { // Add a description for it too if (draw == null) { draw = sheet.createDrawingPatriarch(); } ClientAnchor ca = wb.getCreationHelper().createClientAnchor(); ca.setCol1(c.getColumnIndex()); ca.setCol2(c.getColumnIndex() + 1); ca.setRow1(hr.getRowNum()); ca.setRow2(hr.getRowNum() + 2); Comment cmt = draw.createCellComment(ca); cmt.setAuthor(""); cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i])); cmt.setVisible(false); c.setCellComment(cmt); } } // Have the contents populated populateBody(resource, wb, sheet, properties); // Save it for the template ByteArrayOutputStream baos = new ByteArrayOutputStream(); wb.write(baos); model.put(MODEL_EXCEL, baos.toByteArray()); } }
From source file:com.quanticate.opensource.spreadsheetexcerpt.excerpt.POIExcerpterAndMerger.java
License:Apache License
private void merge(Workbook excerptWB, Workbook fullWB, String[] sheetsToMerge, OutputStream output) throws IOException { // Identify the sheets in both workbooks List<Sheet> sourceSheets = identifySheets(sheetsToMerge, excerptWB); List<Sheet> destSheets = identifySheets(sheetsToMerge, fullWB); // Process each sheet from the excerpt in turn for (int i = 0; i < sheetsToMerge.length; i++) { Sheet source = sourceSheets.get(i); Sheet dest = destSheets.get(i);//from w ww .ja va2 s . c om for (Row srcR : source) { for (Cell srcC : srcR) { if (srcC.getCellType() == Cell.CELL_TYPE_FORMULA || srcC.getCellType() == Cell.CELL_TYPE_ERROR) { // Don't merge these kinds of cells } else { Row destR = dest.getRow(srcR.getRowNum()); if (destR == null) { // Newly added row to the excerpt file, skip this } else { Cell destC = destR.getCell(srcC.getColumnIndex()); if (destC == null && srcC.getCellType() == Cell.CELL_TYPE_BLANK) { // Both are empty, don't need to do anything } else { if (destC == null) destC = destR.createCell(srcC.getColumnIndex(), srcC.getCellType()); // Sync contents if (srcC.getCellType() == Cell.CELL_TYPE_BLANK) { destC.setCellType(Cell.CELL_TYPE_BLANK); } else if (srcC.getCellType() == Cell.CELL_TYPE_BOOLEAN) { destC.setCellValue(srcC.getBooleanCellValue()); } else if (srcC.getCellType() == Cell.CELL_TYPE_NUMERIC) { destC.setCellValue(srcC.getNumericCellValue()); } else if (srcC.getCellType() == Cell.CELL_TYPE_STRING) { destC.setCellValue(srcC.getStringCellValue()); } // Sync formatting rules // TODO } } } } } } // Re-evaluate all the formulas in the destination workbook, now that // we have updated cells in it FormulaEvaluator eval = fullWB.getCreationHelper().createFormulaEvaluator(); eval.evaluateAll(); // Save the new file fullWB.write(output); }
From source file:com.quanticate.opensource.spreadsheetexcerpt.excerpt.TestPOIExcerpter.java
License:Apache License
@Test public void excerptGoesReadOnly() throws Exception { for (Workbook wb : new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() }) { FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); Sheet s = wb.createSheet("Test"); // Numeric formulas Row r1 = s.createRow(0);// ww w.ja v a 2 s. c o m Cell c1 = r1.createCell(0); Cell c2 = r1.createCell(1); Cell c3 = r1.createCell(2); Cell c4 = r1.createCell(3); c1.setCellValue(1); c2.setCellValue(2); c3.setCellFormula("A1+B1"); c4.setCellFormula("(A1+B1)*B1"); // Strings, booleans and errors Row r2 = s.createRow(1); Cell c21 = r2.createCell(0); Cell c22 = r2.createCell(1); Cell c23 = r2.createCell(2); Cell c24 = r2.createCell(3); c21.setCellValue("Testing"); c22.setCellFormula("CONCATENATE(A2,A2)"); c23.setCellFormula("FALSE()"); c24.setCellFormula("A1/0"); // Ensure the formulas are current eval.evaluateAll(); // Run the excerpt File tmp = File.createTempFile("test", ".xls"); wb.write(new FileOutputStream(tmp)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); excerpter.excerpt(new int[] { 0 }, tmp, baos); // Check Workbook newwb = WorkbookFactory.create(new ByteArrayInputStream(baos.toByteArray())); assertEquals(1, newwb.getNumberOfSheets()); s = newwb.getSheetAt(0); r1 = s.getRow(0); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(0).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(1).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(2).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(3).getCellType()); assertEquals(1.0, s.getRow(0).getCell(0).getNumericCellValue(), 0.001); assertEquals(2.0, s.getRow(0).getCell(1).getNumericCellValue(), 0.001); assertEquals(3.0, s.getRow(0).getCell(2).getNumericCellValue(), 0.001); assertEquals(6.0, s.getRow(0).getCell(3).getNumericCellValue(), 0.001); r2 = s.getRow(1); assertEquals(Cell.CELL_TYPE_STRING, r2.getCell(0).getCellType()); assertEquals(Cell.CELL_TYPE_STRING, r2.getCell(1).getCellType()); assertEquals(Cell.CELL_TYPE_BOOLEAN, r2.getCell(2).getCellType()); assertEquals(Cell.CELL_TYPE_BLANK, r2.getCell(3).getCellType()); assertEquals("Testing", s.getRow(1).getCell(0).getStringCellValue()); assertEquals("TestingTesting", s.getRow(1).getCell(1).getStringCellValue()); assertEquals(false, s.getRow(1).getCell(2).getBooleanCellValue()); } }
From source file:com.runwaysdk.dataaccess.io.ExcelExportSheet.java
License:Open Source License
/** * Prepares a new sheet (which represents a type) in the workbook. Fills in all necessary information for the sheet. * //w ww .j a v a 2 s. co m * @return */ public Sheet createSheet(Workbook workbook, CellStyle boldStyle) { CreationHelper helper = workbook.getCreationHelper(); String sheetName = this.getFormattedSheetName(); Sheet sheet = workbook.createSheet(sheetName); Drawing drawing = sheet.createDrawingPatriarch(); Row typeRow = sheet.createRow(0); typeRow.setZeroHeight(true); Row nameRow = sheet.createRow(1); nameRow.setZeroHeight(true); Row labelRow = sheet.createRow(2); int i = 0; for (ExcelColumn column : this.getExpectedColumns()) { writeHeader(sheet, drawing, nameRow, labelRow, i++, column, boldStyle); } for (ExcelColumn column : this.getExtraColumns()) { writeHeader(sheet, drawing, nameRow, labelRow, i++, column, boldStyle); } typeRow.createCell(0).setCellValue(helper.createRichTextString(this.getType())); this.writeRows(sheet); return sheet; }
From source file:com.setu.hsapiassistance.service.ReportService.java
Workbook createReport(List<History> histories) { Workbook wb = new HSSFWorkbook(); //Workbook wb = new XSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("new sheet"); // Create a row and put some cells in it. Rows are 0 based. Row row = sheet.createRow((short) 0); // Create a cell and put a value in it. Cell contactHeader = row.createCell(0); contactHeader.setCellValue("Contact"); Cell dateHeader = row.createCell(1); dateHeader.setCellValue("Date"); Cell actionHeader = row.createCell(2); actionHeader.setCellValue("Action"); for (int i = 0; i < histories.size(); i++) { row = sheet.createRow(i + 1);//w ww . j a v a2 s. c om Cell contact = row.createCell(0); contact.setCellValue(histories.get(i).getEmail()); Cell date = row.createCell(1); date.setCellValue(getFormattedDate(histories.get(i).getDate())); Cell action = row.createCell(2); action.setCellValue(histories.get(i).getAction()); } return wb; }
From source file:com.skt.adcas.lte.action.DownLinkByNMSAction.java
public String selectDailyCellTrafficExcelDownload() { this.log.debug("selectDailyCellTrafficExcelDownload Start"); SqlSession session = null;/*from ww w.j a va2 s. co m*/ FileOutputStream fileOut = null; try { parseParam(); log.debug(this.MFC_CD); Type type = new TypeToken<Map<String, Object>>() { }.getType(); Gson gson = new Gson(); Map<String, Object> map = gson.fromJson(this.JSONDATA, type); log.debug("json data : " + this.JSONDATA); Workbook wb = new HSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); String sheetName = "data"; String safeName = WorkbookUtil.createSafeSheetName(sheetName); //sheet ? jump this.makeTrafficSheet(wb, safeName, map); String writeFolderPath = (String) super.properties.get("TEMP_FOLDER_PATH"); String tempFolder = "/" + UUID.randomUUID().toString(); String xlsFileName = "/DownLinkData.xls"; if (!(new File(writeFolderPath + tempFolder)).mkdir()) { throw new Exception("? ?? ."); } String xlsFileFullPath = writeFolderPath + tempFolder + xlsFileName; fileOut = new FileOutputStream(xlsFileFullPath); wb.write(fileOut); this.msg = "? ? ?"; this.status = "SUCCESS"; this.downloadurl = "download" + tempFolder + xlsFileName; } catch (Exception e) { e.printStackTrace(); this.msg = e.getMessage(); this.status = "ERROR"; this.error = true; if (session != null) { session.rollback(); } e.printStackTrace(); } finally { try { if (fileOut != null) fileOut.close(); } catch (IOException e) { e.printStackTrace(); } if (session != null) { session.close(); } } this.log.debug("selectDailyCellTrafficExcelDownload End"); return SUCCESS; }
From source file:com.skt.adcas.lte.action.DownLinkByNMSAction.java
public String selectDailyCellTrafficCompExcelDownload() { this.log.debug("selectDailyCellTrafficCompExcelDownload Start"); SqlSession session = null;/*from w ww .ja v a 2 s . c om*/ FileOutputStream fileOut = null; try { parseParam(); log.debug(this.MFC_CD); Type type = new TypeToken<Map<String, Object>>() { }.getType(); Gson gson = new Gson(); log.debug("json data : " + this.JSONDATA); Workbook wb = new HSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); // Map<String, Object> map = gson.fromJson(this.JSONDATA, type); String sheetName = " data"; String safeName = WorkbookUtil.createSafeSheetName(sheetName); this.makeTrafficSheet(wb, safeName, map); // Map<String, Object> mapAfter = gson.fromJson(this.JSONDATAAFTER, type); String sheetNameAfter = " data"; String safeNameAfter = WorkbookUtil.createSafeSheetName(sheetNameAfter); this.makeTrafficSheet(wb, safeNameAfter, mapAfter); String writeFolderPath = (String) super.properties.get("TEMP_FOLDER_PATH"); String tempFolder = "/" + UUID.randomUUID().toString(); String xlsFileName = "/DownLinkDataComp.xls"; if (!(new File(writeFolderPath + tempFolder)).mkdir()) { throw new Exception("? ?? ."); } String xlsFileFullPath = writeFolderPath + tempFolder + xlsFileName; fileOut = new FileOutputStream(xlsFileFullPath); wb.write(fileOut); this.msg = "? ? ?"; this.status = "SUCCESS"; this.downloadurl = "download" + tempFolder + xlsFileName; } catch (Exception e) { e.printStackTrace(); this.msg = e.getMessage(); this.status = "ERROR"; this.error = true; if (session != null) { session.rollback(); } e.printStackTrace(); } finally { try { if (fileOut != null) fileOut.close(); } catch (IOException e) { e.printStackTrace(); } if (session != null) { session.close(); } } this.log.debug("selectDailyCellTrafficCompExcelDownload End"); return SUCCESS; }
From source file:com.skt.adcas.lte.action.DownLinkBySTDStatsAction.java
public String selectCellTrafficStatsExcelDownload() { this.log.debug("selectCellTrafficStatsExcelDownload Start"); FileOutputStream fileOut = null; try {//from ww w. j a v a 2 s. c o m //parseParam(); Type type = new TypeToken<Map<String, Object>>() { }.getType(); Gson gson = new Gson(); Map<String, Object> map = gson.fromJson(this.JSONDATA, type); log.debug("json data : " + this.JSONDATA); String searchType = this.SEARCHTYPE; Workbook wb = new HSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); String sheetName = "data"; String safeName = WorkbookUtil.createSafeSheetName(sheetName); //sheet Sheet sheet = wb.createSheet(safeName); createCellTrafficStatsExcelSheet(sheet, map, searchType); String writeFolderPath = (String) super.properties.get("TEMP_FOLDER_PATH"); String tempFolder = "/" + UUID.randomUUID().toString(); String xlsFileName = "/DownLinkStatsData(STD).xls"; if (!(new File(writeFolderPath + tempFolder)).mkdir()) { throw new Exception("? ?? ."); } String xlsFileFullPath = writeFolderPath + tempFolder + xlsFileName; fileOut = new FileOutputStream(xlsFileFullPath); wb.write(fileOut); this.msg = "? ? ?"; this.status = "SUCCESS"; this.downloadurl = "download" + tempFolder + xlsFileName; } catch (Exception e) { this.msg = e.getMessage(); this.status = "ERROR"; this.error = true; e.printStackTrace(); } finally { try { if (fileOut != null) fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } this.log.debug("selectCellTrafficStatsExcelDownload End"); return SUCCESS; }