List of usage examples for org.apache.poi.ss.usermodel Workbook write
void write(OutputStream stream) throws IOException;
From source file:com.springapp.mvc.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/* ww w . j av a2 s .c o m*/ wb = new XSSFWorkbook(); Map<String, CellStyle> styles = createStyles(wb); Sheet sheet = wb.createSheet("Business Plan"); //turn off gridlines sheet.setDisplayGridlines(false); 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-11")); 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 = "businessplan.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); }
From source file:com.ssic.education.provider.controller.ProSupplierController.java
@RequestMapping(value = "/excel") @ResponseBody/*from w w w . ja v a 2 s .co m*/ public ModelAndView exportExcel(SupplierDto supplierDto, HttpServletRequest request, HttpServletResponse response) { SessionInfo info = (SessionInfo) request.getSession().getAttribute(ConfigUtil.SESSIONINFONAME); if (info == null) { return null; } supplierDto.setReceiverId(info.getSupplierId()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.M.d"); Date date = new Date(); String filename = Tools.date2Str(date, "yyyyMMddHHmmss"); HSSFSheet sheet; HSSFCell cell; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); Workbook workbook = new HSSFWorkbook(); sheet = (HSSFSheet) workbook.createSheet(""); try { List<String> titles = new ArrayList<String>(); titles.add("????"); titles.add("???"); // titles.add("????"); // titles.add("??????"); titles.add("????"); titles.add("???"); // titles.add("?"); // titles.add("???"); titles.add("?"); titles.add("?"); int len = titles.size(); HSSFCellStyle headerStyle = (HSSFCellStyle) workbook.createCellStyle(); // ? headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); HSSFFont headerFont = (HSSFFont) workbook.createFont(); // headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); headerFont.setFontHeightInPoints((short) 11); headerStyle.setFont(headerFont); short width = 20, height = 25 * 20; sheet.setDefaultColumnWidth(width); HSSFRow sheetRow = sheet.createRow(0); for (int i = 0; i < len; i++) { // String title = titles.get(i); cell = sheetRow.createCell(i); cell.setCellStyle(headerStyle); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(title); } sheet.getRow(0).setHeight(height); HSSFCellStyle contentStyle = (HSSFCellStyle) workbook.createCellStyle(); // ? contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); DataGrid dg = supplierService.findProSupplier(supplierDto, null); List<SupplierDto> expList = dg.getRows(); List<PageData> varList = new ArrayList<PageData>(); if (!CollectionUtils.isEmpty(expList)) { for (int i = 0; i < expList.size(); i++) { PageData vpd = new PageData(); vpd.put("var1", expList.get(i).getSupplierName()); vpd.put("var2", expList.get(i).getAddress()); // vpd.put("var3", expList.get(i).getFoodServiceCode()); // vpd.put("var4", expList.get(i).getFoodBusinessCode()); vpd.put("var3", expList.get(i).getFoodCirculationCode()); vpd.put("var4", expList.get(i).getFoodProduceCode()); // vpd.put("var7", expList.get(i).getBusinessLicense()); // vpd.put("var8", expList.get(i).getSupplierCode()); vpd.put("var5", expList.get(i).getCorporation()); vpd.put("var6", expList.get(i).getContactWay()); varList.add(vpd); } } for (int i = 0; i < varList.size(); i++) { HSSFRow row = sheet.createRow(i + 1); PageData vpd = varList.get(i); for (int j = 0; j < len; j++) { String varstr = vpd.getString("var" + (j + 1)) != null ? vpd.getString("var" + (j + 1)) : ""; cell = row.createCell(j); HSSFCellStyle cellStyle2 = (HSSFCellStyle) workbook.createCellStyle(); HSSFDataFormat format = (HSSFDataFormat) workbook.createDataFormat(); cellStyle2.setDataFormat(format.getFormat("@")); cell.setCellStyle(cellStyle2); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(varstr); } } OutputStream os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); } catch (Exception e) { } return null; }
From source file:com.ssic.education.provider.controller.WaresController.java
@RequestMapping(value = "/excel") @ResponseBody//from w w w . j av a2s .c o m public ModelAndView exportExcel(ProWaresDto proWaresDto, HttpServletRequest request, HttpServletResponse response) { SessionInfo info = (SessionInfo) request.getSession().getAttribute(ConfigUtil.SESSIONINFONAME); if (info == null) { return null; } proWaresDto.setSupplierId(info.getSupplierId()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.M.d"); Date date = new Date(); String filename = Tools.date2Str(date, "yyyyMMddHHmmss"); HSSFSheet sheet; HSSFCell cell; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); Workbook workbook = new HSSFWorkbook(); sheet = (HSSFSheet) workbook.createSheet(""); try { List<String> titles = new ArrayList<String>(); titles.add("??"); titles.add("???"); titles.add(""); titles.add("?"); titles.add("?"); // titles.add("??"); // titles.add("???"); // titles.add("??"); titles.add("?"); titles.add("???"); titles.add(""); int len = titles.size(); HSSFCellStyle headerStyle = (HSSFCellStyle) workbook.createCellStyle(); // ? headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); HSSFFont headerFont = (HSSFFont) workbook.createFont(); // headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); headerFont.setFontHeightInPoints((short) 11); headerStyle.setFont(headerFont); short width = 20, height = 25 * 20; sheet.setDefaultColumnWidth(width); HSSFRow sheetRow = sheet.createRow(0); for (int i = 0; i < len; i++) { // String title = titles.get(i); cell = sheetRow.createCell(i); cell.setCellStyle(headerStyle); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(title); } sheet.getRow(0).setHeight(height); HSSFCellStyle contentStyle = (HSSFCellStyle) workbook.createCellStyle(); // ? contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); List<ProWaresDto> expList = waresService.findAllWares(proWaresDto, null); List<PageData> varList = new ArrayList<PageData>(); if (!CollectionUtils.isEmpty(expList)) { for (int i = 0; i < expList.size(); i++) { PageData vpd = new PageData(); vpd.put("var1", expList.get(i).getWaresName()); vpd.put("var2", expList.get(i).getAmountUnit()); vpd.put("var3", expList.get(i).getSpec()); vpd.put("var4", ProductClass.getName(expList.get(i).getWaresType())); vpd.put("var5", expList.get(i).getManufacturer()); // vpd.put("var5", expList.get(i).getEnName()); // vpd.put("var6", expList.get(i).getBarCode()); // vpd.put("var7", expList.get(i).getCustomCode()); vpd.put("var6", expList.get(i).getShelfLife()); vpd.put("var7", expList.get(i).getUnit()); vpd.put("var8", expList.get(i).getPlace()); varList.add(vpd); } } for (int i = 0; i < varList.size(); i++) { HSSFRow row = sheet.createRow(i + 1); PageData vpd = varList.get(i); for (int j = 0; j < len; j++) { String varstr = vpd.getString("var" + (j + 1)) != null ? vpd.getString("var" + (j + 1)) : ""; cell = row.createCell(j); HSSFCellStyle cellStyle2 = (HSSFCellStyle) workbook.createCellStyle(); HSSFDataFormat format = (HSSFDataFormat) workbook.createDataFormat(); cellStyle2.setDataFormat(format.getFormat("@")); cell.setCellStyle(cellStyle2); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(varstr); } } OutputStream os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); } catch (Exception e) { } return null; }
From source file:com.stam.excellatin.ExcelLatin.java
public static void main(String[] args) { List<String> options = new ArrayList<>(); int startIndex = 0; for (String arg : args) { if (validOptions.contains(arg)) { options.add(arg);/* w ww . ja va 2 s.co m*/ startIndex++; } } if (args[0].equals("-h") || args.length < 3) { System.out.println("usage: ExcelLatin [options] filenameIn filenameOut columnNames..."); System.out.println("options:"); System.out.println("\t-L\tto Latin (default)"); System.out.println("\t-G\tto Greek"); System.out.println("\t-d\tdon't deaccent"); System.out.println("\t-h\thelp"); } else { boolean greekToLatin = false; boolean latinToGreek = false; Transliterator transliterator = null; if ((!options.contains("-L") && !options.contains("-G")) || options.contains("-L")) { transliterator = Transliterator.getInstance("Greek-Latin/UNGEGN"); System.out.println("\nTransliterating Greek to Latin"); greekToLatin = true; } else if (options.contains("-G")) { transliterator = Transliterator.getInstance("Latin-Greek/UNGEGN"); System.out.println("\nTransliterating Latin to Greek"); latinToGreek = true; } if (transliterator == null) { System.out.println("Not a valid option for the transliteration language"); return; } boolean deAccent = true; if (options.contains("-d")) { deAccent = false; System.out.println("Will not deaccent"); } String fileNameIn = args[startIndex]; String fileNameOut = args[startIndex + 1]; List<String> columnNames = new ArrayList<>(); System.out.println("\nColumns to transliterate\n---------------------------"); for (int i = startIndex + 2; i < args.length; i++) { columnNames.add(args[i]); System.out.println(args[i]); } System.out.println("\n"); try { File file = new File(fileNameIn); if (!file.exists()) { System.out.println("The file " + fileNameIn + " was not found"); return; } Map<String, String> mapTransformations = new HashMap<>(); Scanner sc = new Scanner(new FileReader("map.txt")); while (sc.hasNextLine()) { String greekEntry = sc.next(); String latinEntry = sc.next(); if (greekToLatin) { mapTransformations.put(greekEntry, latinEntry); } else if (latinToGreek) { mapTransformations.put(latinEntry, greekEntry); } } DataFormatter formatter = new DataFormatter(); Workbook wb = WorkbookFactory.create(file); Workbook newWb = null; if (wb instanceof HSSFWorkbook) { newWb = new HSSFWorkbook(); } else if (wb instanceof XSSFWorkbook) { newWb = new XSSFWorkbook(); } FileOutputStream fileOut = new FileOutputStream(fileNameOut); if (newWb != null) { Sheet sheetOut = newWb.createSheet(); Sheet sheet = wb.getSheetAt(0); List<Integer> idxs = new ArrayList<>(); Row row = sheet.getRow(0); for (Cell cell : row) { String cellVal = formatter.formatCellValue(cell); if (cellVal == null || cellVal.trim().equals("")) { break; } if (columnNames.contains(cell.getStringCellValue())) { idxs.add(cell.getColumnIndex()); } } for (Row rowIn : sheet) { Row rowOut = sheetOut.createRow(rowIn.getRowNum()); if (rowIn.getRowNum() == 0) { for (Cell cell : rowIn) { cell.setCellType(Cell.CELL_TYPE_STRING); Cell cellOut = rowOut.createCell(cell.getColumnIndex()); cellOut.setCellValue(cell.getStringCellValue()); } } else { for (Cell cell : rowIn) { cell.setCellType(Cell.CELL_TYPE_STRING); String cellVal = formatter.formatCellValue(cell); String cellNewVal = cellVal; if (idxs.contains(cell.getColumnIndex()) && cellVal != null) { if (mapTransformations.containsKey(cellVal)) { cellNewVal = mapTransformations.get(cellVal); } else { if (deAccent) { cellNewVal = deAccent(transliterator.transform(cellVal)); } else { cellNewVal = transliterator.transform(cellVal); } } } Cell cellOut = rowOut.createCell(cell.getColumnIndex()); cellOut.setCellValue(cellNewVal); } } } System.out.println("Finished!"); newWb.write(fileOut); fileOut.close(); } } catch (IOException | InvalidFormatException ex) { Logger.getLogger(ExcelLatin.class.toString()).log(Level.SEVERE, null, ex); } } }
From source file:com.suomi.carinsurance.export.excel.ExcelService.java
License:Open Source License
/** * //from ww w. j a v a 2 s.c o m * * @param outputStream ? * @param config ? * @param data ? * @param elementClass */ public <T> void export(OutputStream outputStream, ExcelWorkbook config, List<T> data, Class<T> elementClass) { if (outputStream == null) { throw new RuntimeException("Excel outputStream is null"); } if (config == null) { throw new RuntimeException("Excel config is null"); } if (data == null) { return; } try { // ? Workbook workbook = new HSSFWorkbook(); // ? List<ExcelSheet> sheetConfigList = config.getSheetList(); if (sheetConfigList != null && sheetConfigList.size() > 0) { for (ExcelSheet sheetConfig : sheetConfigList) { Sheet sheet = workbook.createSheet(sheetConfig.getName()); // ? List<ExcelField> fieldConfigList = sheetConfig.getFieldList(); if (fieldConfigList != null && fieldConfigList.size() > 0) { int rowIndex = 0; int colIndex = 0; List<String> javaFieldList = new ArrayList<String>(); // ? Row titleRow = sheet.createRow(rowIndex); for (ExcelField fieldConfig : fieldConfigList) { if (fieldConfig != null && fieldConfig.isExport() //&& StringUtil.isNotBlank(fieldConfig.getExcelName()) && StringUtil.isNotBlank(fieldConfig.getJavaName())) { String excelName = fieldConfig.getExcelName(); if (StringUtil.isBlank(excelName)) { Field field = ReflectUtil.getField(elementClass, fieldConfig.getJavaName()); com.suomi.carinsurance.annotation.ExcelField excelField = field .getAnnotation(com.suomi.carinsurance.annotation.ExcelField.class); excelName = excelField.name(); } if (StringUtil.isBlank(excelName)) { continue; } titleRow.createCell(colIndex).setCellValue(excelName); javaFieldList.add(fieldConfig.getJavaName()); colIndex++; } } // ?? if (data.size() < 1) { break; } for (T item : data) { if (item == null) { continue; } rowIndex++; colIndex = 0; Row dataRow = sheet.createRow(rowIndex); for (String javaField : javaFieldList) { Cell dataCell = dataRow.createCell(colIndex); Object fieldValue = ReflectUtil.getFieldValue(item, javaField); if (fieldValue instanceof Boolean) { dataCell.setCellValue((boolean) fieldValue); } else if (fieldValue instanceof Number) { dataCell.setCellValue(((Number) fieldValue).doubleValue()); } else if (fieldValue instanceof BigDecimal) { dataCell.setCellValue(((BigDecimal) fieldValue).doubleValue()); } else if (fieldValue instanceof Date) { dataCell.setCellValue((Date) fieldValue); } else if (fieldValue instanceof Calendar) { dataCell.setCellValue((Calendar) fieldValue); } else if (fieldValue instanceof String) { dataCell.setCellValue((String) fieldValue); } else { dataCell.setCellValue(""); } colIndex++; } } } } } workbook.write(outputStream); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtil.close(outputStream); } }
From source file:com.swordlord.gozer.components.wicket.action.button.generic.GWCsvButton.java
License:Open Source License
private ResourceStreamRequestHandler createTarget(Workbook wb) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try {/* w w w.j av a2 s .c om*/ wb.write(out); } catch (Exception e) { LOG.error(e); return null; } ResourceStreamRequestHandler ret = new ResourceStreamRequestHandler( new BinaryStreamWriter(out, "application/vnd.ms-excel")); try { out.close(); } catch (Exception e) { LOG.error(e); } return ret; }
From source file:com.toba.bll.admin.ReportsDownloadServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from w ww . j a v a 2 s. c om * @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 { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("Users Registered in the Past Month"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("User Name"); row.createCell(1).setCellValue("First Name"); row.createCell(2).setCellValue("Last Name"); row.createCell(3).setCellValue("Registration Date"); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); Date oneMonthAgo = calendar.getTime(); List<User> usersRegisteredInThePastMonth = UserDB.selectUsersRegisteredAfter(oneMonthAgo); HSSFCellStyle dateCellStyle = (HSSFCellStyle) workbook.createCellStyle(); short dateDataFormat = workbook.createDataFormat().getFormat("dd/MM/yyyy"); dateCellStyle.setDataFormat(dateDataFormat); for (int i = 0; i < usersRegisteredInThePastMonth.size(); i++) { User user = usersRegisteredInThePastMonth.get(i); row = sheet.createRow(1 + i); row.createCell(0).setCellValue(user.getUserName()); row.createCell(1).setCellValue(user.getFirstName()); row.createCell(2).setCellValue(user.getLastName()); row.createCell(3).setCellValue(user.getRegistrationDate()); row.getCell(3).setCellStyle(dateCellStyle); } workbook.write(response.getOutputStream()); workbook.close(); response.setHeader("content-disposition", "attachment; filename=users.xls"); response.setHeader("cache-control", "no-cache"); }
From source file:com.tremolosecurity.scale.ui.reports.GenerateSpreadsheet.java
License:Apache License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate"); resp.setHeader("Pragma", "no-cache"); ReportViewer scaleReport = (ReportViewer) req.getSession().getAttribute("scaleReportCached"); Workbook wb = new XSSFWorkbook(); Font font = wb.createFont();/*from w ww . jav a 2s .c om*/ font.setBold(true); Font titleFont = wb.createFont(); titleFont.setBold(true); titleFont.setFontHeightInPoints((short) 16); Sheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(scaleReport.getReportInfo().getName())); //Create a header Row row = sheet.createRow(0); Cell cell = row.createCell(0); RichTextString title = new XSSFRichTextString(scaleReport.getReportInfo().getName()); title.applyFont(titleFont); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); cell.setCellValue(title); row = sheet.createRow(1); cell = row.createCell(0); cell.setCellValue(scaleReport.getReportInfo().getDescription()); sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3)); row = sheet.createRow(2); cell = row.createCell(0); cell.setCellValue(scaleReport.getRunDateTime()); sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3)); row = sheet.createRow(3); int rowNum = 4; if (scaleReport.getResults().getGrouping().isEmpty()) { row = sheet.createRow(rowNum); cell = row.createCell(0); cell.setCellValue("There is no data for this report"); } else { for (ReportGrouping group : scaleReport.getResults().getGrouping()) { for (String colHeader : scaleReport.getResults().getHeaderFields()) { row = sheet.createRow(rowNum); cell = row.createCell(0); RichTextString rcolHeader = new XSSFRichTextString(colHeader); rcolHeader.applyFont(font); cell.setCellValue(rcolHeader); cell = row.createCell(1); cell.setCellValue(group.getHeader().get(colHeader)); rowNum++; } row = sheet.createRow(rowNum); int cellNum = 0; for (String colHeader : scaleReport.getResults().getDataFields()) { cell = row.createCell(cellNum); RichTextString rcolHeader = new XSSFRichTextString(colHeader); rcolHeader.applyFont(font); cell.setCellValue(rcolHeader); cellNum++; } rowNum++; for (Map<String, String> dataRow : group.getData()) { cellNum = 0; row = sheet.createRow(rowNum); for (String colHeader : scaleReport.getResults().getDataFields()) { cell = row.createCell(cellNum); cell.setCellValue(dataRow.get(colHeader)); cellNum++; } rowNum++; } row = sheet.createRow(rowNum); rowNum++; } } resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); wb.write(resp.getOutputStream()); }
From source file:com.tremolosecurity.scalejs.ws.ScaleMain.java
License:Apache License
private void exportToExcel(HttpFilterRequest request, HttpFilterResponse response, Gson gson) throws IOException { int lastslash = request.getRequestURI().lastIndexOf('/'); int secondlastslash = request.getRequestURI().lastIndexOf('/', lastslash - 1); String id = request.getRequestURI().substring(secondlastslash + 1, lastslash); ReportResults res = (ReportResults) request.getSession().getAttribute(id); if (res == null) { response.setStatus(404);/*w ww. j ava 2 s .c o m*/ ScaleError error = new ScaleError(); error.getErrors().add("Report no longer available"); ScaleJSUtils.addCacheHeaders(response); response.getWriter().print(gson.toJson(error).trim()); response.getWriter().flush(); } else { response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate"); response.setHeader("Pragma", "no-cache"); Workbook wb = new XSSFWorkbook(); Font font = wb.createFont(); font.setBold(true); Font titleFont = wb.createFont(); titleFont.setBold(true); titleFont.setFontHeightInPoints((short) 16); Sheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName(res.getName())); //Create a header Row row = sheet.createRow(0); Cell cell = row.createCell(0); RichTextString title = new XSSFRichTextString(res.getName()); title.applyFont(titleFont); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); cell.setCellValue(title); row = sheet.createRow(1); cell = row.createCell(0); cell.setCellValue(res.getDescription()); sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3)); row = sheet.createRow(2); cell = row.createCell(0); //cell.setCellValue(new DateTime().toString("MMMM Do, YYYY h:mm:ss a")); sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3)); row = sheet.createRow(3); int rowNum = 4; if (res.getGrouping().isEmpty()) { row = sheet.createRow(rowNum); cell = row.createCell(0); cell.setCellValue("There is no data for this report"); } else { for (ReportGrouping group : res.getGrouping()) { for (String colHeader : res.getHeaderFields()) { row = sheet.createRow(rowNum); cell = row.createCell(0); RichTextString rcolHeader = new XSSFRichTextString(colHeader); rcolHeader.applyFont(font); cell.setCellValue(rcolHeader); cell = row.createCell(1); cell.setCellValue(group.getHeader().get(colHeader)); rowNum++; } row = sheet.createRow(rowNum); int cellNum = 0; for (String colHeader : res.getDataFields()) { cell = row.createCell(cellNum); RichTextString rcolHeader = new XSSFRichTextString(colHeader); rcolHeader.applyFont(font); cell.setCellValue(rcolHeader); cellNum++; } rowNum++; for (Map<String, String> dataRow : group.getData()) { cellNum = 0; row = sheet.createRow(rowNum); for (String colHeader : res.getDataFields()) { cell = row.createCell(cellNum); cell.setCellValue(dataRow.get(colHeader)); cellNum++; } rowNum++; } row = sheet.createRow(rowNum); rowNum++; } } response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); wb.write(response.getOutputStream()); } }
From source file:com.upbest.utils.AddDimensionedImage.java
License:Apache License
/** * The main entry point to the program. It contains code that demonstrates * one way to use the program./* ww w. j a va2s .c o m*/ * * Note, the code is not restricted to use on new workbooks only. If an * image is to be inserted into an existing workbook. just open that * workbook, gat a reference to a sheet and pass that; * * AddDimensionedImage addImage = new AddDimensionedImage(); * * File file = new File("....... Existing Workbook ......."); * FileInputStream fis = new FileInputStream(file); * Workbook workbook = new HSSFWorkbook(fis); * HSSFSheet sheet = workbook.getSheetAt(0); * addImage.addImageToSheet("C3", sheet, "image.jpg", 30, 20, * AddDimensionedImage.EXPAND.ROW); * * @param args the command line arguments */ public static void main(String[] args) { String imageFile = null; String outputFile = null; FileOutputStream fos = null; Workbook workbook = null; Sheet sheet = null; args = new String[] { "c:/logo1.jpg", "c:/poi/image.xlsx" }; try { if (args.length < 2) { System.err.println("Usage: AddDimensionedImage imageFile outputFile"); return; } workbook = new XSSFWorkbook(); // OR XSSFWorkbook sheet = workbook.createSheet("Picture Test"); imageFile = args[0]; outputFile = args[1]; new AddDimensionedImage().addImageToSheet("B5", sheet, sheet.createDrawingPatriarch(), new File(imageFile).toURI().toURL(), 100, 40, AddDimensionedImage.EXPAND_ROW_AND_COLUMN); fos = new FileOutputStream(outputFile); workbook.write(fos); } catch (FileNotFoundException fnfEx) { System.out.println("Caught an: " + fnfEx.getClass().getName()); System.out.println("Message: " + fnfEx.getMessage()); System.out.println("Stacktrace follows..........."); fnfEx.printStackTrace(System.out); } catch (IOException ioEx) { System.out.println("Caught an: " + ioEx.getClass().getName()); System.out.println("Message: " + ioEx.getMessage()); System.out.println("Stacktrace follows..........."); ioEx.printStackTrace(System.out); } finally { if (fos != null) { try { fos.close(); fos = null; } catch (IOException ioEx) { // I G N O R E } } } }