Example usage for org.apache.poi.xssf.usermodel XSSFWorkbook write

List of usage examples for org.apache.poi.xssf.usermodel XSSFWorkbook write

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFWorkbook write.

Prototype

@SuppressWarnings("resource")
public final void write(OutputStream stream) throws IOException 

Source Link

Document

Write out this document to an Outputstream.

Usage

From source file:data.pkg.ReadWriteExcelFile.java

public static void writeXLSXFile(String fileName, Data data) throws IOException {

    String excelFileName = fileName;//name of excel file

    String sheetName = "Sheet1";//name of sheet

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet(sheetName);

    //iterating r number of rows
    for (int r = 0; r < data.getLength(); r++) {
        XSSFRow row = sheet.createRow(r);

        //iterating c number of columns
        for (int c = 0; c < 2; c++) {
            if (r == 0 && c == 0) {
                XSSFCell cell = row.createCell(c);
                cell.setCellValue("Deslocamento");
            }//w  w  w .j a  va 2 s  .  co m
            if (r == 0 && c == 1) {
                XSSFCell cell = row.createCell(c);
                cell.setCellValue("Fora");
            }
            if (r > 0 && c == 0) {
                XSSFCell cell = row.createCell(c);

                cell.setCellValue(data.getDeslocamento(r - 1));
            }
            if (r > 0 && c == 1) {
                XSSFCell cell = row.createCell(c);

                cell.setCellValue(data.getForca(r - 1));
            }
        }
    }

    FileOutputStream fileOut = new FileOutputStream(excelFileName);

    //write this workbook to an Outputstream.
    wb.write(fileOut);
    fileOut.flush();
    fileOut.close();
}

From source file:dataaccess.WriteResultToFile.java

public static boolean writeDataToXLSXFile(String path, Map<String, ArrayList<String>> result) {

    try {//  w ww  .j  a v a 2 s  .c om
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet spreadsheet = wb.createSheet("result");
        XSSFRow row0 = spreadsheet.createRow(0);
        row0.createCell(0).setCellValue("????");
        row0.createCell(1).setCellValue("");
        row0.createCell(2).setCellValue("?");
        row0.createCell(3).setCellValue("");
        row0.createCell(4).setCellValue("?");
        row0.createCell(5).setCellValue("");
        row0.createCell(6).setCellValue("");
        row0.createCell(7).setCellValue("");
        row0.createCell(8).setCellValue("()");
        row0.createCell(9).setCellValue("(::)");

        Iterator<Map.Entry<String, ArrayList<String>>> resultIterator = result.entrySet().iterator();

        XSSFRow row;
        int rowNum = 1;
        while (resultIterator.hasNext()) {
            Map.Entry<String, ArrayList<String>> resultEntry = resultIterator.next();

            String supplierName = resultEntry.getKey();
            ArrayList<String> info = resultEntry.getValue();
            row = spreadsheet.createRow(rowNum);
            row.createCell(0).setCellValue(supplierName);
            for (int i = 0; i < info.size(); i++) {
                row.createCell(i + 1).setCellValue(info.get(i));
            }
            rowNum = rowNum + 1;
        }
        for (int i = 0; i < 10; i++) {
            spreadsheet.autoSizeColumn(i);
        }
        OutputStream outputStream = new FileOutputStream(path + "\\" + "result.xlsx");
        wb.write(outputStream);
        outputStream.close();
        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:dataaccess.WriteResultToFile.java

public static boolean writeRecommendationInfoToFile(String path, Map<String, ArrayList<String>> result) {

    try {/*from w w  w.  jav a  2  s . c om*/
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet spreadsheet = wb.createSheet("result");
        XSSFRow row0 = spreadsheet.createRow(0);
        row0.createCell(0).setCellValue("???");
        row0.createCell(1).setCellValue("?(?)");
        row0.createCell(2).setCellValue("");
        row0.createCell(3).setCellValue("?");
        row0.createCell(4).setCellValue("");
        row0.createCell(5).setCellValue("?");
        row0.createCell(6).setCellValue("");
        row0.createCell(7).setCellValue("");
        row0.createCell(8).setCellValue("");
        row0.createCell(9).setCellValue("()");
        row0.createCell(10).setCellValue("(::)");

        Iterator<Map.Entry<String, ArrayList<String>>> resultIterator = result.entrySet().iterator();

        XSSFRow row;
        int rowNum = 1;
        while (resultIterator.hasNext()) {
            Map.Entry<String, ArrayList<String>> resultEntry = resultIterator.next();

            String supplierName = resultEntry.getKey();
            ArrayList<String> info = resultEntry.getValue();
            row = spreadsheet.createRow(rowNum);
            row.createCell(0).setCellValue(supplierName);
            for (int i = 0; i < info.size(); i++) {
                row.createCell(i + 1).setCellValue(info.get(i));
            }
            rowNum = rowNum + 1;
        }
        for (int i = 0; i < 10; i++) {
            spreadsheet.autoSizeColumn(i);
        }
        OutputStream outputStream = new FileOutputStream(path + "\\" + "result.xlsx");
        wb.write(outputStream);
        outputStream.close();
        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:dataRepresentation.LUALogger.java

private void close(XSSFWorkbook workbook) {
    try {//from w  w  w .j ava 2 s  .  com
        DateFormat dateFormat = new SimpleDateFormat("-yyyy-MM-dd-HH-mm-ss");
        Date date = new Date();
        System.out.println();
        FileOutputStream out = new FileOutputStream(targetFile + dateFormat.format(date) + fileExt);
        workbook.write(out);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Excel file written successfully!");
}

From source file:DB.TopStockDescriptionList.java

public static FileInputStream openExcelFileOrCreate(String fileName) throws Exception {

    File file = new File(fileName);
    if (file.isFile() && file.exists()) {
        System.out.println(fileName + " file open successfully.");
    } else {/*from   w  w  w .  j a va  2s .c o  m*/
        System.out.println("File doesnt exist : " + fileName);
        FileOutputStream out = new FileOutputStream(new File(fileName));
        XSSFWorkbook workbook = new XSSFWorkbook();
        workbook.write(out);
        out.close();
        file = new File(fileName);
    }

    return new FileInputStream(file);

}

From source file:dbchubreast_web.service.util.FileService.java

License:Open Source License

/** ====================================================================================== */

public void writeExcelFile(OutputStream outputStream, List<String> header, List<Object> listData) {

    // === Blank workbook ===
    XSSFWorkbook workbook = new XSSFWorkbook();

    // === Create a blank sheet ===
    XSSFSheet sheet = workbook.createSheet("EpiMed data " + dateFormat.format(new Date()));

    // === Nb of rows and cells ===
    int rownum = 0;

    // === Header ===
    if (header != null && !header.isEmpty()) {
        Row row = sheet.createRow(rownum++);
        int cellnum = 0;
        for (int i = 0; i < header.size(); i++) {
            Cell cell = row.createCell(cellnum++);
            cell.setCellValue(header.get(i));
        }//  www.j  a  v a  2s .  co m
    }

    // === Data ===
    if (listData != null) {
        for (Iterator<Object> iterator = listData.iterator(); iterator.hasNext();) {
            Object data[] = (Object[]) iterator.next();

            logger.trace(rownum + " " + Arrays.toString(data));

            Row row = sheet.createRow(rownum++);

            int cellnum = 0;
            for (int j = 0; j < data.length; j++) {

                Cell cell = row.createCell(cellnum++);
                cell.setCellType(CellType.STRING);

                boolean isNull = (data[j] == null);
                if (!isNull) {
                    cell.setCellValue(data[j].toString());
                }
            }
        }
    }

    try {
        workbook.write(outputStream);
        workbook.close();
        outputStream.flush();
        outputStream.close();

    } catch (IOException e) {
        logger.debug("XLS error");
        e.printStackTrace();
    }
}

From source file:dbchubreast_web.service.util.FileService.java

License:Open Source License

/** ================================================================================= */

public void writeWorkbook(OutputStream outputStream, XSSFWorkbook workbook) {

    try {//  w ww. j  av a  2  s.  com
        workbook.write(outputStream);
        workbook.close();
        outputStream.flush();
        outputStream.close();

    } catch (IOException e) {
        logger.debug("XLS error");
        e.printStackTrace();
    }
}

From source file:de.bund.bfr.knime.openkrise.db.imports.custom.bfrnewformat.TraceGenerator.java

License:Open Source License

private boolean save(XSSFWorkbook workbook, String filename) {
    try {//from www. j  av a2 s .  c o  m
        File f = new File(filename);
        if (f.exists()) {
            int returnVal = JOptionPane.showConfirmDialog(parent, "Replace file '" + filename + "'?",
                    "Excel file '" + filename + "' exists already", JOptionPane.YES_NO_OPTION);
            if (returnVal == JOptionPane.NO_OPTION)
                return false;
            else if (returnVal == JOptionPane.YES_OPTION)
                ;
            else
                return false;
        }
        POIXMLProperties.CoreProperties coreProp = workbook.getProperties().getCoreProperties();
        coreProp.setCreator("FoodChain-Lab");
        coreProp.setCreated(new Nullable<Date>(new Date(System.currentTimeMillis())));
        // Write the workbook in file system
        FileOutputStream out = new FileOutputStream(f);
        workbook.write(out);
        out.close();
        System.out.println(filename + " written successfully on disk.");
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:de.symeda.sormas.api.doc.DataDictionaryGenerator.java

License:Open Source License

@Test
public void generateDataDictionary() throws FileNotFoundException, IOException {

    XSSFWorkbook workbook = new XSSFWorkbook();

    createEntitySheet(workbook, PersonDto.class, PersonDto.I18N_PREFIX);
    createEntitySheet(workbook, LocationDto.class, LocationDto.I18N_PREFIX);
    createEntitySheet(workbook, CaseDataDto.class, CaseDataDto.I18N_PREFIX);
    createEntitySheet(workbook, HospitalizationDto.class, HospitalizationDto.I18N_PREFIX);
    createEntitySheet(workbook, SymptomsDto.class, SymptomsDto.I18N_PREFIX);
    createEntitySheet(workbook, EpiDataDto.class, EpiDataDto.I18N_PREFIX);
    createEntitySheet(workbook, HealthConditionsDto.class, HealthConditionsDto.I18N_PREFIX);
    createEntitySheet(workbook, PrescriptionDto.class, PrescriptionDto.I18N_PREFIX);
    createEntitySheet(workbook, TreatmentDto.class, TreatmentDto.I18N_PREFIX);
    createEntitySheet(workbook, ClinicalVisitDto.class, ClinicalVisitDto.I18N_PREFIX);
    createEntitySheet(workbook, ContactDto.class, ContactDto.I18N_PREFIX);
    createEntitySheet(workbook, VisitDto.class, VisitDto.I18N_PREFIX);
    createEntitySheet(workbook, SampleDto.class, SampleDto.I18N_PREFIX);
    createEntitySheet(workbook, PathogenTestDto.class, PathogenTestDto.I18N_PREFIX);
    createEntitySheet(workbook, AdditionalTestDto.class, AdditionalTestDto.I18N_PREFIX);
    createEntitySheet(workbook, TaskDto.class, TaskDto.I18N_PREFIX);
    createEntitySheet(workbook, EventDto.class, EventDto.I18N_PREFIX);
    createEntitySheet(workbook, EventParticipantDto.class, EventParticipantDto.I18N_PREFIX);
    createEntitySheet(workbook, FacilityDto.class, FacilityDto.I18N_PREFIX);
    createEntitySheet(workbook, RegionDto.class, RegionDto.I18N_PREFIX);
    createEntitySheet(workbook, DistrictDto.class, DistrictDto.I18N_PREFIX);
    createEntitySheet(workbook, CommunityDto.class, CommunityDto.I18N_PREFIX);
    createEntitySheet(workbook, UserDto.class, UserDto.I18N_PREFIX);

    XssfHelper.addAboutSheet(workbook);/*from   w ww . ja  va 2 s  . c  o m*/

    String filePath = "src/main/resources/doc/SORMAS_Data_Dictionary.xlsx";
    try (OutputStream fileOut = new FileOutputStream(filePath)) {
        workbook.write(fileOut);
    }
    workbook.close();
}

From source file:de.symeda.sormas.api.doc.UserRightsGenerator.java

License:Open Source License

@Test
public void generateUserRights() throws FileNotFoundException, IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();

    // Create User Rights sheet
    String safeName = WorkbookUtil.createSafeSheetName("User Rights");
    XSSFSheet sheet = workbook.createSheet(safeName);

    // Initialize cell styles
    // Authorized style
    XSSFCellStyle authorizedStyle = workbook.createCellStyle();
    authorizedStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    authorizedStyle.setFillForegroundColor(new XSSFColor(new Color(0, 153, 0)));
    authorizedStyle.setBorderBottom(BorderStyle.THIN);
    authorizedStyle.setBorderLeft(BorderStyle.THIN);
    authorizedStyle.setBorderTop(BorderStyle.THIN);
    authorizedStyle.setBorderRight(BorderStyle.THIN);
    authorizedStyle.setBorderColor(BorderSide.BOTTOM, new XSSFColor(Color.BLACK));
    authorizedStyle.setBorderColor(BorderSide.LEFT, new XSSFColor(Color.BLACK));
    authorizedStyle.setBorderColor(BorderSide.TOP, new XSSFColor(Color.BLACK));
    authorizedStyle.setBorderColor(BorderSide.RIGHT, new XSSFColor(Color.BLACK));
    // Unauthorized style
    XSSFCellStyle unauthorizedStyle = workbook.createCellStyle();
    unauthorizedStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    unauthorizedStyle.setFillForegroundColor(new XSSFColor(Color.RED));
    unauthorizedStyle.setBorderBottom(BorderStyle.THIN);
    unauthorizedStyle.setBorderLeft(BorderStyle.THIN);
    unauthorizedStyle.setBorderTop(BorderStyle.THIN);
    unauthorizedStyle.setBorderRight(BorderStyle.THIN);
    unauthorizedStyle.setBorderColor(BorderSide.BOTTOM, new XSSFColor(Color.BLACK));
    unauthorizedStyle.setBorderColor(BorderSide.LEFT, new XSSFColor(Color.BLACK));
    unauthorizedStyle.setBorderColor(BorderSide.TOP, new XSSFColor(Color.BLACK));
    unauthorizedStyle.setBorderColor(BorderSide.RIGHT, new XSSFColor(Color.BLACK));
    // Bold style
    XSSFFont boldFont = workbook.createFont();
    boldFont.setBold(true);//from   w w w . ja v  a  2 s .com
    XSSFCellStyle boldStyle = workbook.createCellStyle();
    boldStyle.setFont(boldFont);

    int rowCounter = 0;

    // Header
    Row headerRow = sheet.createRow(rowCounter++);
    Cell userRightHeadlineCell = headerRow.createCell(0);
    userRightHeadlineCell.setCellValue("User Right");
    userRightHeadlineCell.setCellStyle(boldStyle);
    Cell descHeadlineCell = headerRow.createCell(1);
    descHeadlineCell.setCellValue("Description");
    descHeadlineCell.setCellStyle(boldStyle);
    sheet.setColumnWidth(0, 256 * 35);
    sheet.setColumnWidth(1, 256 * 50);
    for (UserRole userRole : UserRole.values()) {
        String columnCaption = userRole.toString();
        Cell headerCell = headerRow.createCell(userRole.ordinal() + 2);
        headerCell.setCellValue(columnCaption);
        headerCell.setCellStyle(boldStyle);
        sheet.setColumnWidth(userRole.ordinal() + 2, 256 * 14);
    }

    // User right rows
    for (UserRight userRight : UserRight.values()) {
        Row row = sheet.createRow(rowCounter++);

        // User right name
        Cell nameCell = row.createCell(0);
        nameCell.setCellValue(userRight.name());
        nameCell.setCellStyle(boldStyle);

        // User right description
        Cell descCell = row.createCell(1);
        descCell.setCellValue(userRight.toString());

        // Add styled cells for all user roles
        for (UserRole userRole : UserRole.values()) {
            Cell roleRightCell = row.createCell(userRole.ordinal() + 2);
            if (userRole.hasDefaultRight(userRight)) {
                roleRightCell.setCellStyle(authorizedStyle);
                roleRightCell.setCellValue("Yes");
            } else {
                roleRightCell.setCellStyle(unauthorizedStyle);
                roleRightCell.setCellValue("No");
            }
        }
    }

    XssfHelper.addAboutSheet(workbook);

    String filePath = "src/main/resources/doc/SORMAS_User_Rights.xlsx";
    try (OutputStream fileOut = new FileOutputStream(filePath)) {
        workbook.write(fileOut);
    }
    workbook.close();

    //      Desktop.getDesktop().open(new File(filePath));
}