List of usage examples for org.apache.poi.ss.usermodel Workbook write
void write(OutputStream stream) throws IOException;
From source file:com.fjn.helper.common.io.file.office.excel.ExcelUtil.java
License:Apache License
/** * /*from ww w. ja va 2 s . c o m*/ * * @param path * @param fileName * @param workbook */ public static void exportToFile(String path, final String fileName, Workbook workbook) { FileOutputStream out = null; // ? File dir = new File(path); boolean exist = dir.exists(); if (exist) { try { dir = new File(dir + "/" + fileName);// if (!dir.exists()) dir.createNewFile(); } catch (Exception e) { } } else { // ??? try { exist = dir.mkdirs(); dir = new File(dir + "/" + fileName);// dir.createNewFile(); exist = true; } catch (Exception e) { throw new FileDirFaultException(path); } } if (!exist) { throw new FileDirFaultException(path); } try { out = new FileOutputStream(path + "/" + fileName); workbook.write(out); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.fjn.helper.common.io.file.office.excel.ExcelUtil.java
License:Apache License
/** * // w w w . j ava 2 s.c om * * @param response * @param fileName * @param workbook */ public static void exportExcelToBrowser(HttpServletResponse response, String fileName, Workbook workbook) { response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream;charset=UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + FileUtil.getFileNameForDownload(fileName)); OutputStream out = null; BufferedOutputStream bos = null; try { out = response.getOutputStream(); bos = new BufferedOutputStream(out); workbook.write(out); bos.flush(); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { StreamUtil.close(bos); StreamUtil.close(out); } }
From source file:com.fjn.helper.common.io.file.office.excel.ExcelUtil.java
License:Apache License
/** * ?/*www . ja v a2 s . c o m*/ * * @param out * @param fileName * @param workbook */ public static void exportExcelToOutputStream(FileOutputStream out, String fileName, Workbook workbook) { BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(out); workbook.write(out); bos.flush(); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { StreamUtil.close(bos); StreamUtil.close(out); } }
From source file:com.frameworkset.platform.cms.votemanager.VoteMobileController.java
License:Open Source License
public static void sendFile(HttpServletRequest request, HttpServletResponse response, String filename, Workbook workbook, long fileSize) throws Exception { OutputStream out = null;// w w w. j a va 2s . c o m try { if (workbook == null) return; out = response.getOutputStream(); response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));//ISO-8859-1 response.setHeader("Accept-Ranges", "bytes"); workbook.write(out); out.flush(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { try { if (out != null) out.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.gezipu360.cashier.bean.word.UpdateEmbeddedDoc.java
License:Apache License
/** * Called to update the embedded Excel workbook. As the format and structire * of the workbook are known in advance, all this code attempts to do is * write a new value into the first cell on the first row of the first * worksheet. Prior to executing this method, that cell will contain the * value 1.//from w w w. j av a 2s .co m * * @throws org.apache.poi.openxml4j.exceptions.OpenXML4JException * Rather * than use the specific classes (HSSF/XSSF) to handle the embedded * workbook this method uses those defeined in the SS stream. As * a result, it might be the case that a SpreadsheetML file is * opened for processing, throwing this exception if that file is * invalid. * @throws java.io.IOException Thrown if a problem occurs in the underlying * file system. */ public void updateEmbeddedDoc() throws OpenXML4JException, IOException { Workbook workbook = null; Sheet sheet = null; Row row = null; Cell cell = null; PackagePart pPart = null; Iterator<PackagePart> pIter = null; List<PackagePart> embeddedDocs = this.doc.getAllEmbedds(); if (embeddedDocs != null && !embeddedDocs.isEmpty()) { pIter = embeddedDocs.iterator(); while (pIter.hasNext()) { pPart = pIter.next(); if (pPart.getPartName().getExtension().equals(BINARY_EXTENSION) || pPart.getPartName().getExtension().equals(OPENXML_EXTENSION)) { // Get an InputStream from the pacage part and pass that // to the create method of the WorkbookFactory class. Update // the resulting Workbook and then stream that out again // using an OutputStream obtained from the same PackagePart. workbook = WorkbookFactory.create(pPart.getInputStream()); sheet = workbook.getSheetAt(SHEET_NUM); row = sheet.getRow(ROW_NUM); cell = row.getCell(CELL_NUM); cell.setCellValue(NEW_VALUE); workbook.write(pPart.getOutputStream()); } } // Finally, write the newly modified Word document out to file. this.doc.write(new FileOutputStream(this.docFile)); } }
From source file:com.github.autoprimer3.Primer3ResultViewController.java
License:Open Source License
private void writePrimersToExcel(final File f) throws IOException { final Service<Void> service = new Service<Void>() { @Override/* ww w . java2s .co m*/ protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws IOException { BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f)); Workbook wb = new XSSFWorkbook(); CellStyle hlink_style = wb.createCellStyle(); Font hlink_font = wb.createFont(); hlink_font.setUnderline(Font.U_SINGLE); hlink_font.setColor(IndexedColors.BLUE.getIndex()); hlink_style.setFont(hlink_font); CreationHelper createHelper = wb.getCreationHelper(); Sheet listSheet = wb.createSheet(); Sheet detailsSheet = wb.createSheet(); Row row = null; int rowNo = 0; int sheetNo = 0; wb.setSheetName(sheetNo++, "List"); wb.setSheetName(sheetNo++, "Details"); row = listSheet.createRow(rowNo++); String header[] = { "Primer", "Sequence", "Product Size (bp)" }; for (int col = 0; col < header.length; col++) { Cell cell = row.createCell(col); cell.setCellValue(header[col]); } updateMessage("Writing primers . . ."); updateProgress(0, data.size() * 3); int n = 0; for (Primer3Result r : data) { n++; updateMessage("Writing primer list " + n + " . . ."); row = listSheet.createRow(rowNo++); int col = 0; Cell cell = row.createCell(col++); cell.setCellValue(r.getName() + "F"); cell = row.createCell(col++); cell.setCellValue(r.getLeftPrimer()); cell = row.createCell(col++); cell.setCellValue(r.getProductSize()); updateProgress(n, data.size() * 3); updateMessage("Writing primer list " + n + " . . ."); row = listSheet.createRow(rowNo++); col = 0; cell = row.createCell(col++); cell.setCellValue(r.getName() + "R"); cell = row.createCell(col++); cell.setCellValue(r.getRightPrimer()); cell = row.createCell(col++); cell.setCellValue(r.getProductSize()); n++; updateProgress(n, data.size() * 3); } rowNo = 0; row = detailsSheet.createRow(rowNo++); ArrayList<String> detailsHeader = new ArrayList<>(Arrays.asList("Name", "Other IDs", "Left Primer", "Right Primer", "Product Size (bp)", "Region", "in-silico PCR")); if (ispcrResCol.isVisible()) { detailsHeader.add("in-silico PCR Results"); } for (int col = 0; col < detailsHeader.size(); col++) { Cell cell = row.createCell(col); cell.setCellValue(detailsHeader.get(col)); } int m = 0; for (Primer3Result r : data) { m++; updateMessage("Writing details for pair " + m + " . . ."); row = detailsSheet.createRow(rowNo++); int col = 0; Cell cell = row.createCell(col++); cell.setCellValue(r.getName()); cell = row.createCell(col++); cell.setCellValue(r.getTranscripts()); cell = row.createCell(col++); cell.setCellValue(r.getLeftPrimer()); cell = row.createCell(col++); cell.setCellValue(r.getRightPrimer()); cell = row.createCell(col++); cell.setCellValue(r.getProductSize()); cell = row.createCell(col++); cell.setCellValue(r.getRegion()); cell = row.createCell(col++); if (r.getIsPcrUrl() != null) { cell.setCellValue("isPCR"); org.apache.poi.ss.usermodel.Hyperlink hl = createHelper .createHyperlink(org.apache.poi.ss.usermodel.Hyperlink.LINK_URL); hl.setAddress(r.getIsPcrUrl()); cell.setHyperlink(hl); cell.setCellStyle(hlink_style); } else { cell.setCellValue(""); } if (ispcrResCol.isVisible()) { cell = row.createCell(col++); if (r.getIsPcrResults() != null) { cell.setCellValue(r.getIsPcrResults()); } else { cell.setCellValue(""); } } updateProgress(n + m, data.size() * 3); } updateMessage("Wrote " + data.size() + " primer pairs to file."); wb.write(bo); bo.close(); return null; } }; } }; service.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { Action response = Dialogs.create().title("Done").masthead("Finished writing") .message("Primers successfully written to " + f.getAbsolutePath() + "\n\nDo you want to open " + "this file now?") .actions(Dialog.ACTION_YES, Dialog.ACTION_NO).styleClass(Dialog.STYLE_CLASS_NATIVE) .showConfirm(); if (response == Dialog.ACTION_YES) { try { openFile(f); } catch (IOException ex) { Action openFailed = Dialogs.create().title("Open failed") .masthead("Could not open output file") .message("Exception encountered when attempting to open " + "the saved file. See below:") .styleClass(Dialog.STYLE_CLASS_NATIVE).showException(ex); } } progressBar.progressProperty().unbind(); progressBar.setVisible(false); summaryLabel.textProperty().unbind(); summaryLabel.setText(summary); closeButton.setDisable(false); closeMenuItem.setDisable(false); setCheckIsPcrButton(); } }); service.setOnCancelled(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { Dialogs writeCancelled = Dialogs.create().title("Writing Cancelled") .masthead("Cancelled writing to file").message("User cancelled writing primers to file.") .styleClass(Dialog.STYLE_CLASS_NATIVE); writeCancelled.showInformation(); progressBar.progressProperty().unbind(); progressBar.setVisible(false); summaryLabel.textProperty().unbind(); summaryLabel.setText(summary); closeButton.setDisable(false); closeMenuItem.setDisable(false); setCheckIsPcrButton(); } }); service.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { Action writeFailed = Dialogs.create().title("Writing failed") .masthead("Could not write primers to file") .message("Exception encountered when attempting to write " + "primers to file. See below:") .styleClass(Dialog.STYLE_CLASS_NATIVE).showException(e.getSource().getException()); progressBar.progressProperty().unbind(); progressBar.setVisible(false); summaryLabel.textProperty().unbind(); summaryLabel.setText(summary); closeButton.setDisable(false); closeMenuItem.setDisable(false); setCheckIsPcrButton(); } }); progressBar.setVisible(true); progressBar.progressProperty().bind(service.progressProperty()); summaryLabel.textProperty().bind(service.messageProperty()); closeButton.setDisable(true); closeMenuItem.setDisable(true); checkIsPcrButton.setText("Cancel"); checkIsPcrButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { service.cancel(); } }); service.start(); }
From source file:com.github.camellabs.iot.cloudlet.geofencing.service.DefaultRouteService.java
License:Apache License
@Override public byte[] exportRoutes(String client, String format) { try {//from w ww . j a va 2 s .c om List<List<String>> exportedRoutes = exportRoutes(client); Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("Routes report for " + client); for (int i = 0; i < exportedRoutes.size(); i++) { Row row = sheet.createRow(i); for (int j = 0; j < exportedRoutes.get(i).size(); j++) { row.createCell(j).setCellValue(exportedRoutes.get(i).get(j)); } } ByteArrayOutputStream xlsBytes = new ByteArrayOutputStream(); workbook.write(xlsBytes); xlsBytes.close(); return xlsBytes.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.github.lucapino.sheetmaker.parsers.mediainfo.MediaInfoExtractor.java
private void print(String rootPath) throws Exception { FileFilter filter = new FileFilter() { @Override/*from w w w . java2 s. com*/ public boolean accept(File pathname) { String lowerCaseName = pathname.getName().toLowerCase(); return (lowerCaseName.endsWith("ifo") && lowerCaseName.startsWith("vts")) || lowerCaseName.endsWith("mkv") || lowerCaseName.endsWith("iso") || lowerCaseName.endsWith("avi"); } }; // parse all the tree under rootPath File rootFolder = new File(rootPath); File[] files = rootFolder.listFiles(); Arrays.sort(files); Map<File, List<File>> mediaMap = new TreeMap<>(); for (File file : files) { System.out.println(file.getName()); // name of the folder -> name of media List<File> fileList; if (file.isDirectory()) { fileList = recurseSubFolder(filter, file); if (!fileList.isEmpty()) { System.out.println("adding " + fileList); mediaMap.put(file, fileList); } } else { if (filter.accept(file)) { fileList = new ArrayList<>(); fileList.add(file); System.out.println("adding " + fileList); mediaMap.put(file, fileList); } } } Set<File> fileNamesSet = mediaMap.keySet(); File outputFile = new File("/home/tagliani/tmp/HD-report.xls"); Workbook wb = new HSSFWorkbook(new FileInputStream(outputFile)); Sheet sheet = wb.createSheet("Toshiba"); MediaInfo MI = new MediaInfo(); int j = 0; for (File mediaFile : fileNamesSet) { List<File> filesList = mediaMap.get(mediaFile); for (File fileInList : filesList) { List<String> audioTracks = new ArrayList<>(); List<String> videoTracks = new ArrayList<>(); List<String> subtitlesTracks = new ArrayList<>(); MI.Open(fileInList.getAbsolutePath()); String durationInt = MI.Get(MediaInfo.StreamKind.General, 0, "Duration", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); System.out.println(fileInList.getName() + " -> " + durationInt); if (StringUtils.isNotEmpty(durationInt) && Integer.valueOf(durationInt) >= 60 * 60 * 1000) { Row row = sheet.createRow(j); String duration = MI.Get(MediaInfo.StreamKind.General, 0, "Duration/String", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); // Create a cell and put a value in it. row.createCell(0).setCellValue(WordUtils.capitalizeFully(mediaFile.getName())); if (fileInList.getName().toLowerCase().endsWith("iso") || fileInList.getName().toLowerCase().endsWith("ifo")) { row.createCell(1).setCellValue("DVD"); } else { row.createCell(1) .setCellValue(FilenameUtils.getExtension(fileInList.getName()).toUpperCase()); } row.createCell(2).setCellValue(FileUtils.byteCountToDisplaySize(FileUtils.sizeOf(mediaFile))); // row.createCell(3).setCellValue(fileInList.getAbsolutePath()); row.createCell(3).setCellValue(duration); // MPEG-2 720x576 @ 25fps 16:9 String format = MI.Get(MediaInfo.StreamKind.Video, 0, "Format", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); row.createCell(4).setCellValue(format); String width = MI.Get(MediaInfo.StreamKind.Video, 0, "Width", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); String height = MI.Get(MediaInfo.StreamKind.Video, 0, "Height", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); row.createCell(5).setCellValue(width + "x" + height); String fps = MI.Get(MediaInfo.StreamKind.Video, 0, "FrameRate", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); row.createCell(6).setCellValue(fps); String aspectRatio = MI.Get(MediaInfo.StreamKind.Video, 0, "DisplayAspectRatio/String", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); row.createCell(7).setCellValue(aspectRatio); int audioStreamNumber = MI.Count_Get(MediaInfo.StreamKind.Audio); for (int i = 0; i < audioStreamNumber; i++) { String audioTitle = MI.Get(MediaInfo.StreamKind.Audio, i, "Title", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); String language = MI.Get(MediaInfo.StreamKind.Audio, i, "Language/String3", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); String codec = MI.Get(MediaInfo.StreamKind.Audio, i, "Codec", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); String channels = MI.Get(MediaInfo.StreamKind.Audio, i, "Channel(s)", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); String sampleRate = MI.Get(MediaInfo.StreamKind.Audio, i, "SamplingRate/String", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); // AC3 ITA 5.1 48.0KHz StringBuilder sb = new StringBuilder(); if (StringUtils.isEmpty(audioTitle)) { sb.append(codec).append(" ").append(language.toUpperCase()).append(" ") .append(channels); } else { sb.append(audioTitle); } sb.append(" ").append(sampleRate); audioTracks.add(sb.toString()); } int textStreamNumber = MI.Count_Get(MediaInfo.StreamKind.Text); for (int i = 0; i < textStreamNumber; i++) { String textLanguage = MI.Get(MediaInfo.StreamKind.Text, i, "Language/String", MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name); subtitlesTracks.add(textLanguage); } MI.Close(); row.createCell(8).setCellValue(audioTracks.toString()); row.createCell(9).setCellValue(subtitlesTracks.toString()); j++; } } // System.out.println(mediaName); } try (FileOutputStream fileOut = new FileOutputStream(outputFile)) { wb.write(fileOut); } }
From source file:com.github.luischavez.lat.excel.Excel.java
License:Open Source License
public File generate(String groupName, LocalDateTime dateTime) { String datetime = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).replaceAll("-", "_") .replaceAll(":", "_").replaceAll("\\.", "_"); String path = System.getProperty("user.dir").concat("/excel/").concat(datetime).concat("/"); File file = new File(path); if (!file.exists()) { file.mkdirs();//from w ww.j a va 2s. c om } file = new File(path.concat(groupName).concat(".xls")); Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(groupName); this.setContent(workbook, sheet, groupName); for (int i = 0; i < 11; i++) { sheet.autoSizeColumn(i); } try (FileOutputStream outputStream = new FileOutputStream(file)) { workbook.write(outputStream); } catch (IOException ex) { throw new RuntimeException(ex); } return file; }
From source file:com.github.mutationmapper.MutationMapperResultViewController.java
License:Open Source License
private void writeResultsToExcel(final File f) throws IOException { final Service<Void> service = new Service<Void>() { @Override/* w ww .j a va 2s. co m*/ protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws IOException { BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f)); Workbook wb = new XSSFWorkbook(); //CellStyle hlink_style = wb.createCellStyle(); //Font hlink_font = wb.createFont(); //hlink_font.setUnderline(Font.U_SINGLE); //hlink_font.setColor(IndexedColors.BLUE.getIndex()); //hlink_style.setFont(hlink_font); //CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet(); Row row = null; int rowNo = 0; row = sheet.createRow(rowNo++); String header[] = { "#", "Symbol", "Gene", "Transcript", "Genomic Coordinate", "Ref", "Var", "CDS", "Consequence", "CDS Consequence", "Protein Consequence", "Exon/Intron", "Colocated Variants", "Polyphen", "Sift", "Seq Input" }; for (int col = 0; col < header.length; col++) { Cell cell = row.createCell(col); cell.setCellValue(header[col]); } updateMessage("Writing results . . ."); updateProgress(0, displayData.size()); int n = 0; for (MutationMapperResult r : displayData) { n++; updateMessage("Writing result " + n + " . . ."); row = sheet.createRow(rowNo++); int col = 0; ArrayList<String> resultsToWrite = getResultArray(r); for (String s : resultsToWrite) { Cell cell = row.createCell(col++); cell.setCellValue(s); } updateProgress(n, displayData.size()); } updateMessage("Wrote " + displayData.size() + " results to file."); wb.write(bo); bo.close(); return null; } }; } }; service.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("File Saved"); alert.setHeaderText("Displayed results saved to " + f.getName()); alert.setContentText("Open this file now?"); ButtonType yesButton = ButtonType.YES; ButtonType noButton = ButtonType.NO; alert.getButtonTypes().setAll(yesButton, noButton); Optional<ButtonType> response = alert.showAndWait(); if (response.get() == yesButton) { try { openFile(f); } catch (Exception ex) { Alert openError = getExceptionDialog(ex); openError.setTitle("Open Failed"); openError.setHeaderText("Could not open ouput file."); openError.setContentText( "Exception encountered when attempting to open " + "the saved file. See below:"); openError.showAndWait(); } } } }); service.setOnCancelled(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { Alert writeCancelled = new Alert(AlertType.INFORMATION); writeCancelled.setTitle("Cancelled writing to file"); writeCancelled.setHeaderText("User cancelled writing primers to file."); writeCancelled.showAndWait(); } }); service.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent e) { Alert writeFailed = getExceptionDialog(e.getSource().getException()); writeFailed.setTitle("Write Failed"); writeFailed.setHeaderText("Could not write ouput file."); writeFailed.setContentText( "Exception encountered when attempting to write " + "results to file. See below:"); writeFailed.showAndWait(); } }); service.start(); }