List of usage examples for org.apache.poi.ss.usermodel Workbook write
void write(OutputStream stream) throws IOException;
From source file:it.drwolf.ridire.util.async.ExcelGenerator.java
License:Apache License
@Asynchronous public void generateExcelTable(ExcelDataGenerator excelDataGenerator) { excelDataGenerator.setProgress(0);/* ww w . j av a2s . c om*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.cwbConcordancer.setForma(excelDataGenerator.getForma()); this.cwbConcordancer.setContextGroupingLength(excelDataGenerator.getContextGroupingLength()); this.cwbConcordancer.setContextLength(excelDataGenerator.getContextLength()); this.cwbConcordancer.setLemma(excelDataGenerator.getLemma()); this.cwbConcordancer.setPhrase(excelDataGenerator.getPhrase()); this.cwbConcordancer.setPos(excelDataGenerator.getPos()); this.cwbConcordancer.setSortBy(excelDataGenerator.getSortBy()); this.cwbConcordancer.setSortOrder(excelDataGenerator.getSortOrder()); this.cwbConcordancer.setToBeVisualized(excelDataGenerator.getToBeVisualized()); this.cwbConcordancer.setFunctionalMetadatum(excelDataGenerator.getFunctionalMetadatum()); this.cwbConcordancer.setSemanticMetadatum(excelDataGenerator.getSemanticMetadatum()); Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(DocumentDownloader.CONCORDANZE); int rowNumber = 0; int results4DownloadSize = this.cwbConcordancer.getResults4DownloadSize(); // System.out.println("Query size: " + results4DownloadSize); int i = 0; for (int start = 0; start < results4DownloadSize; start += ExcelGenerator.PAGE_SIZE) { List<CWBResult> results4Download = this.cwbConcordancer.getResults4Download(start, ExcelGenerator.PAGE_SIZE); for (CWBResult itemWithContext : results4Download) { Row row = sheet.createRow(rowNumber); ++rowNumber; row.createCell(0).setCellValue(itemWithContext.getLeftContext().toString()); row.createCell(1).setCellValue(itemWithContext.getSearchedText()); row.createCell(2).setCellValue(itemWithContext.getRightContext().toString()); excelDataGenerator.setProgress(Math.round(++i / (results4DownloadSize * 1.0f) * 100)); } } try { workbook.write(baos); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } excelDataGenerator.setFileReady(true); excelDataGenerator.setBaos(baos); excelDataGenerator.setProgress(100); excelDataGenerator.setInProgress(false); }
From source file:it.drwolf.ridire.util.async.ExcelGenerator.java
License:Apache License
@Asynchronous public void generateFLTable(ExcelDataGenerator excelDataGenerator) { excelDataGenerator.setProgress(0);/*from ww w. jav a 2 s . c o m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.cwbFrequencyList.setFunctionalMetadatum(excelDataGenerator.getFunctionalMetadatum()); this.cwbFrequencyList.setSemanticMetadatum(excelDataGenerator.getSemanticMetadatum()); this.cwbFrequencyList.setFrequencyBy(excelDataGenerator.getFrequencyBy()); this.cwbFrequencyList.setQuantity(excelDataGenerator.getQuantity()); this.cwbFrequencyList.setThreshold(excelDataGenerator.getThreshold()); Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(DocumentDownloader.CONCORDANZE); int rowNumber = 0; this.cwbFrequencyList.calculateFrequencyList(); int results4DownloadSize = this.cwbFrequencyList.getFrequencyList().size(); // System.out.println("Query size: " + results4DownloadSize); int i = 0; for (int start = 0; start < results4DownloadSize; start += ExcelGenerator.PAGE_SIZE) { List<FrequencyItem> results4Download = this.cwbFrequencyList.getFrequencyList().subList(start, Math.min(start + ExcelGenerator.PAGE_SIZE, results4DownloadSize)); for (FrequencyItem frequencyItem : results4Download) { Row row = sheet.createRow(rowNumber); ++rowNumber; row.createCell(0).setCellValue(frequencyItem.getFormaPosLemma()); if (excelDataGenerator.getFrequencyBy().equals("PoS-forma") || excelDataGenerator.getFrequencyBy().equals("PoS-lemma")) { row.createCell(1).setCellValue(frequencyItem.getPos()); row.createCell(2).setCellValue(frequencyItem.getFrequency()); } else { row.createCell(1).setCellValue(frequencyItem.getFrequency()); } excelDataGenerator.setProgress(Math.round(++i / (results4DownloadSize * 1.0f) * 100)); } } try { workbook.write(baos); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } excelDataGenerator.setFileReady(true); excelDataGenerator.setBaos(baos); excelDataGenerator.setProgress(100); excelDataGenerator.setInProgress(false); }
From source file:it.eng.spagobi.engines.console.exporter.CreateExportFileAction.java
License:Mozilla Public License
public void service(SourceBean request, SourceBean response) { String dataSetLabel;//from w w w. j a v a2 s .c o m String dataSetHeadersLabel; String mimeType; String responseType; String locale; JSONArray jsonArray; IDataSet dataSet; IDataSet dataSetHeaders; IDataStore dataStore; IDataStore dataStoreHeaders; File file = null; logger.debug("IN"); Monitor monitor = MonitorFactory.start("SpagoBI_Console.CreateExportFileAction.service"); try { super.service(request, response); Assert.assertNotNull(getConsoleEngineInstance(), "It's not possible to execute " + this.getActionName() + " service before having properly created an instance of EngineInstance class"); Assert.assertNotNull(getConsoleEngineInstance().getDataSetServiceProxy(), "It's not possible to execute " + this.getActionName() + " service before having properly created an instance of DatasetServiceProxy class"); dataSetLabel = getAttributeAsString(DATASET_LABEL); logger.debug("Parameter [" + DATASET_LABEL + "] is equals to [" + dataSetLabel + "]"); Assert.assertTrue(!StringUtilities.isEmpty(dataSetLabel), "Parameter [" + DATASET_LABEL + "] cannot be null or empty"); dataSetHeadersLabel = getAttributeAsString(DATASET_HEADERS_LABEL); logger.debug("Parameter [" + DATASET_HEADERS_LABEL + "] is equals to [" + dataSetHeadersLabel + "]"); locale = getAttributeAsString(LOCALE); logger.debug("Parameter [" + LOCALE + "] is equals to [" + locale + "]"); mimeType = getAttributeAsString(MIME_TYPE); logger.debug("Parameter [" + MIME_TYPE + "] is equal to [" + mimeType + "]"); if (mimeType == null) { logger.warn("Parameter [" + MIME_TYPE + "] has not been valorized"); mimeType = DEFAULT_MIME_TYPE; logger.debug("Parameter [" + MIME_TYPE + "] has been set equal to [" + mimeType + "]"); } responseType = getAttributeAsString(RESPONSE_TYPE); logger.debug("Parameter [" + RESPONSE_TYPE + "] is equal to [" + responseType + "]"); if (!RESPONSE_TYPE_INLINE.equalsIgnoreCase(responseType) && !RESPONSE_TYPE_ATTACHMENT.equalsIgnoreCase(responseType)) { logger.warn("Value [" + responseType + "] is not a valid for parameter [" + RESPONSE_TYPE + "]"); responseType = RESPONSE_TYPE_ATTACHMENT; logger.debug("Parameter [" + RESPONSE_TYPE + "] has been set equal to [" + responseType + "]"); } ConsoleEngineConfig conf = ConsoleEngineConfig.getInstance(); String test = getAttributeAsString(META); logger.debug("Parameter [" + META + "] is equal to [" + test + "]"); Object m = getAttribute(META); try { jsonArray = getAttributeAsJSONArray(META); logger.debug("Parameter [" + META + "] is equal to [" + jsonArray.toString(4) + "]"); } catch (Throwable t) { logger.debug("Not a json array: " + test); jsonArray = new JSONArray(); JSONObject obj = getAttributeAsJSONObject(META); jsonArray.put(obj); } dataSet = null; try { dataSet = getConsoleEngineInstance().getDataSetServiceProxy().getDataSetByLabel(dataSetLabel); } catch (Throwable t) { throw new SpagoBIServiceException( "Impossible to find a dataset whose label is [" + dataSetLabel + "]", t); } Assert.assertNotNull(dataSet, "Impossible to find a dataset whose label is [" + dataSetLabel + "]"); //read the dataset with headers dataSetHeaders = null; dataStoreHeaders = null; if (dataSetHeadersLabel != null && !dataSetHeadersLabel.equals("")) { try { dataSetHeaders = getConsoleEngineInstance().getDataSetServiceProxy() .getDataSetByLabel(dataSetHeadersLabel); } catch (Throwable t) { throw new SpagoBIServiceException( "Impossible to find a dataset whose label is [" + dataSetHeadersLabel + "]", t); } Assert.assertNotNull(dataSet, "Impossible to find a dataset whose label is [" + dataSetHeadersLabel + "]"); Map params = getConsoleEngineInstance().getAnalyticalDrivers(); params.put(LOCALE, locale); dataSetHeaders.setParamsMap(params); dataSetHeaders.setUserProfileAttributes(UserProfileUtils .getProfileAttributes((UserProfile) this.getEnv().get(EngineConstants.ENV_USER_PROFILE))); dataSetHeaders.loadData(); dataStoreHeaders = dataSetHeaders.getDataStore(); Assert.assertNotNull(dataStoreHeaders, "The dataStore returned by loadData method of the class [" + dataSetHeaders.getClass().getName() + "] cannot be null"); } Map params = getConsoleEngineInstance().getAnalyticalDrivers(); params.put(LOCALE, locale); dataSet.setParamsMap(params); dataSet.setUserProfileAttributes(UserProfileUtils .getProfileAttributes((UserProfile) this.getEnv().get(EngineConstants.ENV_USER_PROFILE))); dataSet.loadData(); dataStore = dataSet.getDataStore(); Assert.assertNotNull(dataStore, "The dataStore returned by loadData method of the class [" + dataSet.getClass().getName() + "] cannot be null"); // dataStore decoration .... Object resultNumber = dataStore.getMetaData().getProperty("resultNumber"); if (resultNumber == null) dataStore.getMetaData().setProperty("resultNumber", new Integer((int) dataStore.getRecordsCount())); IDataSource ds = getConsoleEngineInstance().getDataSource(); DataSourceUtilities dsu = new DataSourceUtilities(ds); Vector extractedFields = dsu.readFields(dataSet.getQuery().toString()); List extractedFieldsMetaData = new ArrayList<IFieldMetaData>(); if (jsonArray != null && jsonArray.length() > 0) { int fieldNo = dataStore.getMetaData().getFieldCount(); for (int i = 0; i < fieldNo; i++) { dataStore.getMetaData().getFieldMeta(i).setProperty("visible", Boolean.FALSE); } List actionColumns = new ArrayList(); for (int i = 0; i < fieldNo; i++) { IFieldMetaData fFound = dataStore.getMetaData().getFieldMeta(i); String fieldHeader = getFieldHeader(fFound.getName(), jsonArray, dataStore, dataStoreHeaders, locale); if (fieldHeader != null) { Field headerF = new Field(fieldHeader, "java.lang.String", 100); extractedFields.add(headerF); fFound.setProperty("visible", Boolean.TRUE); fFound.setAlias(fieldHeader); fFound.setProperty("index", i); extractedFieldsMetaData.add(fFound); } } /* for(int k = 0; k < jsonArray.length(); k++){ JSONObject resultHeaders = jsonArray.getJSONObject(k); Iterator it = resultHeaders.keys(); while(it.hasNext()) { String key = (String)it.next(); JSONObject header = resultHeaders.getJSONObject(key); String fieldHeader = header.optString("header", ""); String fieldHeaderType = header.optString("headerType", ""); // // in case of dynamic headers gets the value from the dataset (of data) if (fieldHeaderType.equalsIgnoreCase("dataset")){ int posHeader = dataStore.getMetaData().getFieldIndex(fieldHeader); int fieldValsize = ((List)dataStore.getFieldValues(posHeader)).size(); if(fieldValsize != 0){ fieldHeader =((List)dataStore.getFieldValues(posHeader)).get(0).toString(); }else{ fieldHeader = null; } }else if (fieldHeaderType.equalsIgnoreCase("datasetI18N") && dataStoreHeaders != null){ //gets the header value from the specific dataset (only with labels: code - label - locale) int headersFieldNo = dataStoreHeaders.getMetaData().getFieldCount(); //adds index informations to the metadata properties for(int i = 0; i < headersFieldNo; i++) { dataStoreHeaders.getMetaData().getFieldMeta(i).setProperty("index", i+1); } // gets the specific label using the code and the locale int posCode = (dataStoreHeaders.getMetaData().getFieldIndex("code") != -1) ? dataStoreHeaders.getMetaData().getFieldIndex("code") : dataStoreHeaders.getMetaData().getFieldIndex("CODE"); int posLabel = (dataStoreHeaders.getMetaData().getFieldIndex("label") != -1) ? dataStoreHeaders.getMetaData().getFieldIndex("label") : dataStoreHeaders.getMetaData().getFieldIndex("LABEL"); int posLocale = (dataStoreHeaders.getMetaData().getFieldIndex("locale") != -1) ? dataStoreHeaders.getMetaData().getFieldIndex("locale") : dataStoreHeaders.getMetaData().getFieldIndex("LOCALE"); List filterCodes = new ArrayList<String>(); List filterValues = new ArrayList<String>(); filterCodes.add(posCode); filterValues.add(fieldHeader); filterCodes.add(posLocale); filterValues.add(locale); List headersFieldValues = (List)dataStoreHeaders.findRecords(filterCodes, filterValues); if (headersFieldValues != null && headersFieldValues.size() > 0){ Record headerRec = (Record)headersFieldValues.get(0); IField headerField = null; if (headerRec != null){ headerField = (IField) headerRec.getFieldAt(posLabel); } String label = (headerField != null) ? headerField.toString() : ""; if(label != null && !("").equalsIgnoreCase(label)){ fieldHeader = label; } } }else if (fieldHeaderType.equalsIgnoreCase("I18N")){ //gets the header value from the locale files //EnginConf tmp = conf.getEngineConfig(); //System.out.println(tmp); logger.debug("Export headers by locale file doesn't supported yet!"); } if (fieldHeader != null){ } } }*/ dataStore.getMetaData().setProperty("actionColumns", actionColumns); } params = new HashMap(); params.put("pagination", "false"); String docName = getExportName(request); String fileExtension = null; if ("application/vnd.ms-excel".equalsIgnoreCase(mimeType)) { logger.debug("export excel"); fileExtension = "xls"; ExporterExcel exp = new ExporterExcel(dataStore); long numberOfRows = dataStore.getRecordsCount(); String configLimit = (String) conf.getProperty("EXPORT_ROWS_LIMIT"); if (configLimit == null) { configLimit = "65000"; } if (numberOfRows >= Long.parseLong(configLimit)) { numberOfRows = Long.parseLong(configLimit); logger.info("Result set exceded maximum rows number " + configLimit); } exp.setNumberOfRows(numberOfRows); exp.setExtractedFields(extractedFields); exp.setExtractedFieldsMetaData(extractedFieldsMetaData); Workbook wb = exp.export(); file = File.createTempFile(docName, "." + fileExtension); FileOutputStream stream = new FileOutputStream(file); wb.write(stream); stream.flush(); stream.close(); } else if ("text/csv".equalsIgnoreCase(mimeType)) { logger.debug("export CSV"); fileExtension = "csv"; ExporterCSV exp = new ExporterCSV(dataStore); exp.setExtractedFields(extractedFields); exp.setExtractedFieldsMetaData(extractedFieldsMetaData); CSVDocument csvDocument = exp.export(); logger.debug("A CSV document has to be written with " + csvDocument.getHeader().size() + " headers and " + csvDocument.getRows().size() + " rows"); file = File.createTempFile(docName, "." + fileExtension); FileWriter fw = null; try { fw = new FileWriter(file); exp.write(csvDocument, fw); } catch (Exception e) { logger.error("Error in writing the CSV object document", e); } finally { if (fw != null) { fw.flush(); fw.close(); } } } try { JSONObject jsonResponse = new JSONObject(); String name = file.getName().substring(0, file.getName().lastIndexOf('.')); String extension = file.getName().substring(file.getName().lastIndexOf('.') + 1); jsonResponse.put("name", name); jsonResponse.put("extension", extension); writeBackToClient(new JSONSuccess(jsonResponse)); } catch (IOException ioe) { throw new SpagoBIEngineException("Impossible to write back the responce to the client", ioe); } } catch (Throwable t) { throw SpagoBIEngineServiceExceptionHandler.getInstance().getWrappedException(getActionName(), getEngineInstance(), t); } finally { monitor.stop(); logger.debug("OUT"); } }
From source file:it.eng.spagobi.engines.qbe.services.core.ExportResultAction.java
License:Mozilla Public License
private void exportIntoXLS(boolean writeBackResponseInline, String mimeType, IStatement statement, String sqlQuery, Vector extractedFields) throws EMFInternalError, IOException, FileNotFoundException, SpagoBIEngineException { IDataStore dataStore = getDataStore(statement, sqlQuery); Locale locale = (Locale) getEngineInstance().getEnv().get(EngineConstants.ENV_LOCALE); QbeXLSExporter exp = new QbeXLSExporter(dataStore, locale); exp.setExtractedFields(extractedFields); Workbook wb = exp.export(); File file = File.createTempFile("workbook", ".xls"); FileOutputStream stream = new FileOutputStream(file); wb.write(stream); stream.flush();//from ww w.j a v a2 s . c o m stream.close(); try { writeBackToClient(file, null, writeBackResponseInline, "workbook.xls", mimeType); } catch (IOException ioe) { throw new SpagoBIEngineException("Impossible to write back the responce to the client", ioe); } finally { if (file != null && file.exists()) { try { file.delete(); } catch (Exception e) { logger.warn("Impossible to delete temporary file " + file, e); } } } }
From source file:it.eng.spagobi.engines.qbe.services.core.ExportResultAction.java
License:Mozilla Public License
private void exportIntoXLSX(boolean writeBackResponseInline, String mimeType, IStatement statement, String sqlQuery, Vector extractedFields) throws EMFInternalError, IOException, FileNotFoundException, SpagoBIEngineException { IDataStore dataStore = getDataStore(statement, sqlQuery); Locale locale = (Locale) getEngineInstance().getEnv().get(EngineConstants.ENV_LOCALE); QbeXLSExporter exp = new QbeXLSExporter(dataStore, locale); exp.setExtractedFields(extractedFields); Workbook wb = exp.export(); File file = File.createTempFile("workbook", ".xlsx"); FileOutputStream stream = new FileOutputStream(file); wb.write(stream); stream.flush();//from w w w . jav a 2 s . c o m stream.close(); try { writeBackToClient(file, null, writeBackResponseInline, "workbook.xlsx", mimeType); } catch (IOException ioe) { throw new SpagoBIEngineException("Impossible to write back the responce to the client", ioe); } finally { if (file != null && file.exists()) { try { file.delete(); } catch (Exception e) { logger.warn("Impossible to delete temporary file " + file, e); } } } }
From source file:it.eng.spagobi.engines.worksheet.services.export.ExportWorksheetAction.java
License:Mozilla Public License
public void exportToXLS(WorkSheetXLSExporter exporter, JSONObject worksheetJSON, JSONArray metadataPropertiesJSON, JSONArray parametersJSON, OutputStream stream) throws Exception { int sheetsNumber = worksheetJSON.getInt(SHEETS_NUM); Workbook wb = exporter.createNewWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); if (metadataPropertiesJSON != null && metadataPropertiesJSON.length() > 0) { exportMetadataToXLS(wb, exporter, createHelper, metadataPropertiesJSON, parametersJSON); }//from ww w. ja v a 2s. c o m JSONArray exportedSheets = worksheetJSON.getJSONArray(EXPORTED_SHEETS); JSONArray fieldOptions = WorkSheetSerializationUtils.getFieldOptions(worksheetJSON); for (int i = 0; i < sheetsNumber; i++) { // sheets could be null if containing charts in massive export if (!exportedSheets.isNull(i)) { logger.debug("found non empty sheet at index " + i); JSONObject sheetJ = exportedSheets.getJSONObject(i); JSONObject optionalFilters = sheetJ.optJSONObject(QbeEngineStaticVariables.FILTERS); String sheetName = sheetJ.getString(SHEET); List<WhereField> splittingWF = getSplittingFieldValues(optionalFilters, sheetName); WhereField splittingWhereField = null; if (splittingWF == null || splittingWF.size() == 0) { exportSheetToXLS(wb, sheetJ, fieldOptions, exporter, createHelper, splittingWhereField); } else { for (int y = 0; y < splittingWF.size(); y++) { splittingWhereField = splittingWF.get(y); exportSheetToXLS(wb, sheetJ, fieldOptions, exporter, createHelper, splittingWhereField); } } } else { logger.debug("found empty sheet at index " + i); } } wb.write(stream); stream.flush(); }
From source file:it.polimi.diceH2020.launcher.controller.DownloadsController.java
License:Apache License
@RequestMapping(value = "/download", method = RequestMethod.GET) @ResponseBody/*from www .j ava2s .c o m*/ void downloadPartialExcel(@RequestParam(value = "id") Long id, HttpServletResponse response) { SimulationsManager manager = simulationsManagerRepository.findOne(id); Workbook wb = excelWriter.createWorkbook(manager); try { //response.setContentType("application/ms-excel;charset=utf-8"); response.setContentType("application/vnd.ms-excel;charset=utf-8"); //response.setContentType(new MediaType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet")); response.setHeader("Content-Disposition", "attachment;filename = results.xls"); wb.write(response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } }
From source file:it.redev.parco.ext.ExportableModelEntityQuery.java
License:Open Source License
public void download() { refresh();//from w w w . ja v a 2 s.c o m FacesContext fc = FacesContext.getCurrentInstance(); ExternalContext ec = fc.getExternalContext(); ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide. ec.setResponseContentType("application/vnd.ms-excel"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename. //ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown. ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + getFileName() + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead. // Now you can write the InputStream of the file to the above OutputStream the usual way. // ... try { Workbook xls = export(); OutputStream output = ec.getResponseOutputStream(); xls.write(output); } catch (IOException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { log.error(StringUtils.getStackTrace(e)); } catch (IntrospectionException e) { log.error(StringUtils.getStackTrace(e)); } catch (IllegalAccessException e) { log.error(StringUtils.getStackTrace(e)); } catch (InvocationTargetException e) { log.error(StringUtils.getStackTrace(e)); } fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed. }
From source file:it.unitn.elisco.servlet.admin.DownloadQuestionsServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from ww w . j av a2 s. c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ContextDAO ctxdao = new ContextDAO(); QuestionDAO qdao = new QuestionDAO(); long context_id; try { context_id = Long.parseLong(request.getParameter("id")); } catch (NumberFormatException ex) { LOG.warn("Invalid request parameter passed to servlet: " + ex.getMessage()); request.setAttribute("error", "Invalid request parameter"); request.getRequestDispatcher("/error.jsp").forward(request, response); return; } // Check if the context hidden field sent a valid context_id if (context_id != -1) { Context context = ctxdao.getContext(context_id); // Check if the context exists if (context != null) { // Get student questions List<Question> questions = qdao.getQuestions(context); // Get excel file for questions Workbook excel = Utilities.getExcelFromQuestionList( context.getCourse().getName() + " - " + context.getTitle() + " - Domande degli studenti", questions); // Set response header response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.setHeader("Content-Disposition", "attachment; filename=" + context.getCourse().getName() + " - " + "Domande.xlsx"); // Write to response stream ServletOutputStream out = null; try { out = response.getOutputStream(); excel.write(out); out.flush(); } finally { if (out != null) try { out.close(); } catch (IOException ignore) { } } } else { request.setAttribute("error", "Errore inatteso nei dati della richiesta"); request.getRequestDispatcher("/error.jsp").forward(request, response); } } else { request.setAttribute("error", "Errore inatteso nei dati della richiesta"); request.getRequestDispatcher("/error.jsp").forward(request, response); } }
From source file:itpreneurs.itp.report.archive.BusinessPlan.java
License:Apache License
public static void main(String[] args) throws Exception { Workbook wb; // if(args.length > 0 && args[0].equals("-xls")) wb = new // HSSFWorkbook(); // else wb = new XSSFWorkbook(); wb = new XSSFWorkbook(); Map<String, CellStyle> styles = createStyles(wb); Sheet sheet = wb.createSheet("Business Plan"); // turn off gridlines sheet.setDisplayGridlines(false);//from w ww . j a v a 2 s. c o m sheet.setPrintGridlines(false); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); // the following three statements are required only for HSSF sheet.setAutobreaks(true); printSetup.setFitHeight((short) 1); printSetup.setFitWidth((short) 1); // the header row: centered text in 48pt font Row headerRow = sheet.createRow(0); headerRow.setHeightInPoints(12.75f); for (int i = 0; i < titles.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(titles[i]); cell.setCellStyle(styles.get("header")); } // columns for 11 weeks starting from 9-Jul Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); calendar.setTime(fmt.parse("9-Jul")); calendar.set(Calendar.YEAR, year); for (int i = 0; i < 11; i++) { Cell cell = headerRow.createCell(titles.length + i); cell.setCellValue(calendar); cell.setCellStyle(styles.get("header_date")); calendar.roll(Calendar.WEEK_OF_YEAR, true); } // freeze the first row sheet.createFreezePane(0, 1); Row row; Cell cell; int rownum = 1; for (int i = 0; i < data.length; i++, rownum++) { row = sheet.createRow(rownum); if (data[i] == null) continue; for (int j = 0; j < data[i].length; j++) { cell = row.createCell(j); String styleName; boolean isHeader = i == 0 || data[i - 1] == null; switch (j) { case 0: if (isHeader) { styleName = "cell_b"; cell.setCellValue(Double.parseDouble(data[i][j])); } else { styleName = "cell_normal"; cell.setCellValue(data[i][j]); } break; case 1: if (isHeader) { styleName = i == 0 ? "cell_h" : "cell_bb"; } else { styleName = "cell_indented"; } cell.setCellValue(data[i][j]); break; case 2: styleName = isHeader ? "cell_b" : "cell_normal"; cell.setCellValue(data[i][j]); break; case 3: styleName = isHeader ? "cell_b_centered" : "cell_normal_centered"; cell.setCellValue(Integer.parseInt(data[i][j])); break; case 4: { calendar.setTime(fmt.parse(data[i][j])); calendar.set(Calendar.YEAR, year); cell.setCellValue(calendar); styleName = isHeader ? "cell_b_date" : "cell_normal_date"; break; } case 5: { int r = rownum + 1; String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")"; cell.setCellFormula(fmla); styleName = isHeader ? "cell_bg" : "cell_g"; break; } default: styleName = data[i][j] != null ? "cell_blue" : "cell_normal"; } cell.setCellStyle(styles.get(styleName)); } } // group rows for each phase, row numbers are 0-based sheet.groupRow(4, 6); sheet.groupRow(9, 13); sheet.groupRow(16, 18); // set column widths, the width is measured in units of 1/256th of a // character width sheet.setColumnWidth(0, 256 * 6); sheet.setColumnWidth(1, 256 * 33); sheet.setColumnWidth(2, 256 * 20); sheet.setZoom(3, 4); // Write the output to a file String file = "/Users/vincentgong/Documents/workspaces/Resource/itpreneurs/report/businessplan.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); }