Example usage for org.apache.poi.ss.usermodel Workbook write

List of usage examples for org.apache.poi.ss.usermodel Workbook write

Introduction

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

Prototype

void write(OutputStream stream) throws IOException;

Source Link

Document

Write out this workbook to an Outputstream.

Usage

From source file:edu.ucsd.hep.roofitexplorer.view.misc.SimpleWorkspaceMemberListPanel.java

License:Apache License

private void saveAsXLSWithDialog() {
    if (saveAsXLSFileChooser == null) {
        saveAsXLSFileChooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("XLS files", "xls");
        saveAsXLSFileChooser.setFileFilter(filter);
    }//from  www  .  jav  a  2 s  . c om

    int result = saveAsXLSFileChooser.showSaveDialog(this);
    if (result != JFileChooser.APPROVE_OPTION)
        return;

    try {
        File file = saveAsXLSFileChooser.getSelectedFile();

        // create a new file
        FileOutputStream out = new FileOutputStream(file);

        // this method should take into account filtering and sorting
        Workbook wb = ExcelWorkbookProducer.makeHSSFWorkbook(this.table, "members of workspace");

        wb.write(out);
        out.close();

    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(this, "error saving spreadsheet file: " + ex);
    }

}

From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java

License:Apache License

/**
 * [Flow #-2]  ?  : ? ?  ? ?    ?/*from  w w  w.  j  av a 2s.c o  m*/
 */
@Test
public void testModifyCellContents() throws Exception {

    try {
        String content = "Use \n with word wrap on to create a new line";
        short rownum = 2;
        int cellnum = 2;

        LOGGER.debug("testModifyCellContents start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testModifyCellContents.xls");

        if (!EgovFileUtil.isExistsFile(sb.toString())) {
            Workbook wbT = new HSSFWorkbook();
            wbT.createSheet();

            //  ? ?
            excelService.createWorkbook(wbT, sb.toString());
        }

        //  ? 
        Workbook wb = excelService.loadWorkbook(sb.toString());
        LOGGER.debug("testModifyCellContents after loadWorkbook....");

        Sheet sheet = wb.getSheetAt(0);
        Font f2 = wb.createFont();
        CellStyle cs = wb.createCellStyle();
        cs = wb.createCellStyle();

        cs.setFont(f2);
        //Word Wrap MUST be turned on
        cs.setWrapText(true);

        Row row = sheet.createRow(rownum);
        row.setHeight((short) 0x349);
        Cell cell = row.createCell(cellnum);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue(new HSSFRichTextString(content));
        cell.setCellStyle(cs);

        sheet.setColumnWidth(20, (int) ((50 * 8) / ((double) 1 / 20)));

        //excelService.writeWorkbook(wb);

        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //  ? 
        Workbook wb1 = excelService.loadWorkbook(sb.toString());

        Sheet sheet1 = wb1.getSheetAt(0);
        Row row1 = sheet1.getRow(rownum);
        Cell cell1 = row1.getCell(cellnum);

        // ? ?  ?
        LOGGER.debug("cell ###{}###", cell1.getRichStringCellValue());
        LOGGER.debug("cont ###{}###", content);

        assertNotSame("TEST", cell1.getRichStringCellValue().toString());
        assertEquals(content, cell1.getRichStringCellValue().toString());

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testModifyCellContents end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java

License:Apache License

/**
 * [Flow #-4]   ?  :  ? ? ?(Header, Footer)? 
 *//*from  ww  w. j  av  a 2s .  co  m*/
@Test
public void testModifyDocAttribute() throws Exception {

    try {
        LOGGER.debug("testModifyDocAttribute start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testModifyDocAttribute.xls");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wbTmp = new HSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        Workbook wb = excelService.loadWorkbook(sb.toString());
        LOGGER.debug("testModifyCellContents after loadWorkbook....");

        Sheet sheet = wb.createSheet("doc test sheet");

        Row row = sheet.createRow(1);
        Cell cell = row.createCell(1);
        cell.setCellValue(new HSSFRichTextString("Header/Footer Test"));

        // Header
        Header header = sheet.getHeader();
        header.setCenter("Center Header");
        header.setLeft("Left Header");
        header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") + HSSFHeader.fontSize((short) 16)
                + "Right Stencil-Normal Italic font and size 16");

        // Footer
        Footer footer = sheet.getFooter();
        footer.setCenter(HSSFHeader.font("Fixedsys", "Normal") + HSSFHeader.fontSize((short) 12) + "- 1 -");
        LOGGER.debug("Style is ...{}", HSSFHeader.font("Fixedsys", "Normal"),
                HSSFHeader.fontSize((short) 12) + "- 1 -");
        footer.setLeft("Left Footer");
        footer.setRight("Right Footer");

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        assertTrue(EgovFileUtil.isExistsFile(sb.toString()));

        //////////////////////////////////////////////////////////////////////////
        // ?
        Workbook wbT = excelService.loadWorkbook(sb.toString());
        Sheet sheetT = wbT.getSheet("doc test sheet");

        Header headerT = sheetT.getHeader();
        assertEquals("Center Header", headerT.getCenter());
        assertEquals("Left Header", headerT.getLeft());
        assertEquals(HSSFHeader.font("Stencil-Normal", "Italic") + HSSFHeader.fontSize((short) 16)
                + "Right Stencil-Normal Italic font and size 16", headerT.getRight());

        Footer footerT = sheetT.getFooter();
        assertEquals("Right Footer", footerT.getRight());
        assertEquals("Left Footer", footerT.getLeft());
        assertEquals(HSSFHeader.font("Fixedsys", "Normal") + HSSFHeader.fontSize((short) 12) + "- 1 -",
                footerT.getCenter());

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testModifyDocAttribute end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java

License:Apache License

/**
 * [Flow #-5]    :  ?? ?  ? ?  //from  w w w  .  jav a  2 s .c  om
 */
@Test
public void testGetCellContents() throws Exception {

    try {
        LOGGER.debug("testGetCellContents start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testGetCellContents.xls");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wbTmp = new HSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        Workbook wb = excelService.loadWorkbook(sb.toString());
        LOGGER.debug("testGetCellContents after loadWorkbook....");

        Sheet sheet = wb.createSheet("cell test sheet");

        CellStyle cs = wb.createCellStyle();
        cs = wb.createCellStyle();
        cs.setWrapText(true);

        for (int i = 0; i < 100; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < 5; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(new HSSFRichTextString("row " + i + ", cell " + j));
                cell.setCellStyle(cs);
            }
        }

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //////////////////////////////////////////////////////////////////////////
        // ?
        Workbook wbT = excelService.loadWorkbook(sb.toString());
        Sheet sheetT = wbT.getSheet("cell test sheet");

        for (int i = 0; i < 100; i++) {
            Row row1 = sheetT.getRow(i);
            for (int j = 0; j < 5; j++) {
                Cell cell1 = row1.getCell(j);
                LOGGER.debug("row {}, cell {} : {}", i, j, cell1.getRichStringCellValue());
                assertEquals("row " + i + ", cell " + j, cell1.getRichStringCellValue().toString());
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testGetCellContents end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelServiceTest.java

License:Apache License

/**
 * [Flow #-6]  ?  :  ? ?(?, ? )? /*from  w  ww .  ja  v  a2 s . c  o  m*/
 */
@Test
public void testModifyCellAttribute() throws Exception {

    try {
        LOGGER.debug("testModifyCellAttribute start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testModifyCellAttribute.xls");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wbTmp = new HSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        Workbook wb = excelService.loadWorkbook(sb.toString());
        LOGGER.debug("testModifyCellAttribute after loadWorkbook....");

        Sheet sheet = wb.createSheet("cell test sheet2");
        //           sheet.setColumnWidth((short) 3, (short) 200);   // column Width

        CellStyle cs = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontHeight((short) 16);
        font.setBoldweight((short) 3);
        font.setFontName("fixedsys");

        cs.setFont(font);
        cs.setAlignment(CellStyle.ALIGN_RIGHT); // cell 
        cs.setWrapText(true);

        for (int i = 0; i < 100; i++) {
            Row row = sheet.createRow(i);
            //              row.setHeight((short)300); // row? height 

            for (int j = 0; j < 5; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(new HSSFRichTextString("row " + i + ", cell " + j));
                cell.setCellStyle(cs);
            }
        }

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //////////////////////////////////////////////////////////////////////////
        // ?
        Workbook wbT = excelService.loadWorkbook(sb.toString());
        Sheet sheetT = wbT.getSheet("cell test sheet2");
        LOGGER.debug("getNumCellStyles : {}", wbT.getNumCellStyles());

        CellStyle cs1 = wbT.getCellStyleAt((short) (wbT.getNumCellStyles() - 1));

        Font fontT = ((HSSFCellStyle) cs1).getFont(wbT);
        LOGGER.debug("font getFontHeight : {}", fontT.getFontHeight());
        LOGGER.debug("font getBoldweight : {}", fontT.getBoldweight());
        LOGGER.debug("font getFontName : {}", fontT.getFontName());
        LOGGER.debug("getAlignment : {}", cs1.getAlignment());
        LOGGER.debug("getWrapText : {}", cs1.getWrapText());

        for (int i = 0; i < 100; i++) {
            Row row1 = sheetT.getRow(i);
            for (int j = 0; j < 5; j++) {
                Cell cell1 = row1.getCell(j);
                LOGGER.debug("row {}, cell {} : {}", i, j, cell1.getRichStringCellValue());
                assertEquals(16, fontT.getFontHeight());
                assertEquals(3, fontT.getBoldweight());
                assertEquals(CellStyle.ALIGN_RIGHT, cs1.getAlignment());
                assertTrue(cs1.getWrapText());
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testModifyCellAttribute end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelXSSFServiceTest.java

License:Apache License

/**
 * [Flow #-4]   ?  :  ? ? ?(Header, Footer)? 
 *///from  w w  w  .j ava 2  s .  c o  m
@Test
public void testModifyDocAttribute() throws Exception {

    try {
        LOGGER.debug("testModifyDocAttribute start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testModifyDocAttribute.xlsx");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wbTmp = new XSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        Workbook wb = excelService.loadWorkbook(sb.toString(), new XSSFWorkbook());
        LOGGER.debug("testModifyCellContents after loadWorkbook....");

        Sheet sheet = wb.createSheet("doc test sheet");

        Row row = sheet.createRow(1);
        Cell cell = row.createCell(1);
        cell.setCellValue(new XSSFRichTextString("Header/Footer Test"));

        // Header
        Header header = sheet.getHeader();
        header.setCenter("Center Header");
        header.setLeft("Left Header");
        header.setRight(XSSFOddHeader.stripFields("&IRight Stencil-Normal Italic font and size 16"));

        // Footer
        Footer footer = (XSSFOddFooter) sheet.getFooter();
        footer.setCenter(XSSFOddHeader.stripFields("Fixedsys"));
        LOGGER.debug("Style is ... {}", XSSFOddHeader.stripFields("Fixedsys"));
        footer.setLeft("Left Footer");
        footer.setRight("Right Footer");

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        assertTrue(EgovFileUtil.isExistsFile(sb.toString()));

        //////////////////////////////////////////////////////////////////////////
        // ?
        Workbook wbT = excelService.loadWorkbook(sb.toString(), new XSSFWorkbook());
        Sheet sheetT = wbT.getSheet("doc test sheet");

        Header headerT = sheetT.getHeader();
        assertEquals("Center Header", headerT.getCenter());
        assertEquals("Left Header", headerT.getLeft());
        assertEquals(XSSFOddHeader.stripFields("Right Stencil-Normal Italic font and size 16"),
                headerT.getRight());

        Footer footerT = sheetT.getFooter();
        assertEquals("Right Footer", footerT.getRight());
        assertEquals("Left Footer", footerT.getLeft());
        assertEquals(XSSFOddHeader.stripFields("Fixedsys"), footerT.getCenter());

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testModifyDocAttribute end....");
    }
}

From source file:egovframework.rte.fdl.excel.EgovExcelXSSFServiceTest.java

License:Apache License

/**
 * [Flow #-5]    :  ?? ?  ? ?  //from w w w. j  av  a2  s .co  m
 */
@Test
public void testGetCellContents() throws Exception {

    try {
        LOGGER.debug("testGetCellContents start....");

        StringBuffer sb = new StringBuffer();
        sb.append(fileLocation).append("/").append("testGetCellContents.xlsx");

        if (EgovFileUtil.isExistsFile(sb.toString())) {
            EgovFileUtil.delete(new File(sb.toString()));

            LOGGER.debug("Delete file....{}", sb.toString());
        }

        Workbook wbTmp = new XSSFWorkbook();
        wbTmp.createSheet();

        //  ? ?
        excelService.createWorkbook(wbTmp, sb.toString());

        //  ? 
        Workbook wb = excelService.loadWorkbook(sb.toString(), new XSSFWorkbook());
        LOGGER.debug("testGetCellContents after loadWorkbook....");

        Sheet sheet = wb.createSheet("cell test sheet");

        CellStyle cs = wb.createCellStyle();
        cs = wb.createCellStyle();
        cs.setWrapText(true);

        for (int i = 0; i < 100; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < 5; j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue(new XSSFRichTextString("row " + i + ", cell " + j));
                cell.setCellStyle(cs);
            }
        }

        //  ? 
        FileOutputStream out = new FileOutputStream(sb.toString());
        wb.write(out);
        out.close();

        //////////////////////////////////////////////////////////////////////////
        // ?
        Workbook wbT = excelService.loadWorkbook(sb.toString(), new XSSFWorkbook());
        Sheet sheetT = wbT.getSheet("cell test sheet");

        for (int i = 0; i < 100; i++) {
            Row row1 = sheetT.getRow(i);
            for (int j = 0; j < 5; j++) {
                Cell cell1 = row1.getCell(j);
                LOGGER.debug("row {}, cell : {}", i, j, cell1.getRichStringCellValue());
                assertEquals("row " + i + ", cell " + j, cell1.getRichStringCellValue().toString());
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.toString());
        throw new Exception(e);
    } finally {
        LOGGER.debug("testGetCellContents end....");
    }
}

From source file:egovframework.rte.fdl.excel.impl.EgovExcelServiceImpl.java

License:Apache License

/**
* Workbook ? ? ?? ?.//  w w  w .j  av  a  2 s.  co m
* 
* @param wb
* @param filepath
* @return
* @throws Exception
*/
public Workbook createWorkbook(Workbook wb, String filepath)
        throws BaseException, FileNotFoundException, IOException {

    String fullFileName = filepath;

    LOGGER.debug("EgovExcelServiceImpl.createWorkbook : templatePath is {}",
            FilenameUtils.getFullPath(fullFileName));

    //   ?
    if (!EgovFileUtil.isExistsFile(FilenameUtils.getFullPath(fullFileName))) {
        LOGGER.debug("make dir {}", FilenameUtils.getFullPath(fullFileName));

        try {
            FileUtils.forceMkdir(new File(FilenameUtils.getFullPath(fullFileName)));
        } catch (IOException e) {
            throw new IOException(
                    "Cannot create directory for path: " + FilenameUtils.getFullPath(fullFileName));
        }
    }

    FileOutputStream fileOut = new FileOutputStream(fullFileName);

    LOGGER.debug("EgovExcelServiceImpl.createWorkbook : templatePath is {}", fullFileName);

    try {
        LOGGER.debug("ExcelServiceImpl loadExcelObject ...");

        wb.write(fileOut);

    } catch (Exception e) {
        LOGGER.error(getMessageSource().getMessage("error.excel.runtime.error",
                new Object[] { "createWorkbook" }, Locale.getDefault()), e);
    } finally {
        LOGGER.debug("ExcelServiceImpl loadExcelObject end...");
        fileOut.close();
    }

    return wb;
}

From source file:eleanalysis.SampleLibrary.java

/**
 * writes a report in the form of an excel spreadsheet that is exported.
 * Stage variable is for using a filechooser to pick where to save file.
 * @param myStage Stage is for saving file using FileChooser
 * @throws FileNotFoundException /*from   w  ww .ja v  a  2  s .co m*/
 */
public void writeReport(Stage myStage) throws FileNotFoundException {
    FileChooser pickFile = new FileChooser();
    pickFile.setInitialDirectory(new File("C:\\Users\\Yan\\Documents\\NetBeansProjects\\EleAnalysis\\"));
    pickFile.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("XLS", "*.xls"),
            new FileChooser.ExtensionFilter("XLSX", "*.xlsx"));
    File writeFile = pickFile.showSaveDialog(myStage);
    FileOutputStream fileOut;
    fileOut = new FileOutputStream(writeFile);

    Workbook wb = new HSSFWorkbook();
    Sheet sheet1 = wb.createSheet("WDXRF");
    sheet1.setDefaultColumnWidth(15);
    // Create a cell space
    for (int i = 0; i < ElementUtils.skf.length + 5; i++) {
        Row tempR = sheet1.createRow(i);
        for (int j = 0; j <= array.size(); j++) {
            Cell tempC = tempR.createCell(j);
        }
    }
    CellStyle csCenter = wb.createCellStyle();
    csCenter.setAlignment(CellStyle.ALIGN_CENTER);
    csCenter.setBorderTop(CellStyle.BORDER_THIN);
    csCenter.setBorderLeft(CellStyle.BORDER_THIN);
    csCenter.setBorderRight(CellStyle.BORDER_THIN);
    csCenter.setBorderBottom(CellStyle.BORDER_THIN);
    CellStyle csRight = wb.createCellStyle();
    csRight.setAlignment(CellStyle.ALIGN_RIGHT);
    csRight.setBorderTop(CellStyle.BORDER_THIN);
    csRight.setBorderLeft(CellStyle.BORDER_THIN);
    csRight.setBorderRight(CellStyle.BORDER_THIN);
    csRight.setBorderBottom(CellStyle.BORDER_THIN);
    CellStyle csLeft = wb.createCellStyle();
    csLeft.setAlignment(CellStyle.ALIGN_LEFT);
    csLeft.setBorderTop(CellStyle.BORDER_THIN);
    csLeft.setBorderLeft(CellStyle.BORDER_THIN);
    csLeft.setBorderRight(CellStyle.BORDER_THIN);
    csLeft.setBorderBottom(CellStyle.BORDER_THIN);

    //Top Row
    sheet1.getRow(0).setHeightInPoints(25);
    sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, array.size()));
    sheet1.getRow(0).getCell(0).setCellValue("WDXRF Analysis");
    sheet1.getRow(0).getCell(0).setCellStyle(csCenter);
    sheet1.addMergedRegion(new CellRangeAddress(1, 1, 0, array.size()));

    //Second Row
    sheet1.getRow(1).getCell(0).setCellValue("Conc as Wt%");
    sheet1.getRow(1).getCell(0).setCellStyle(csCenter);

    // Third Row
    sheet1.getRow(2).setHeightInPoints(35);
    sheet1.getRow(2).getCell(0).setCellValue("Common Oxides/Oxication States");
    sheet1.getRow(2).getCell(0).setCellStyle(csLeft);
    for (int j = 1; j <= array.size(); j++) {
        sheet1.getRow(2).getCell(j).setCellStyle(csLeft);
        sheet1.getRow(2).getCell(j).setCellValue(array.get(j - 1).getName());
    }

    //Fourth Row
    sheet1.getRow(3).getCell(0).setCellValue("% Detectable");
    sheet1.getRow(3).getCell(0).setCellStyle(csLeft);
    for (int j = 1; j <= array.size(); j++) {
        sheet1.getRow(3).getCell(j).setCellValue("0.00");
        sheet1.getRow(3).getCell(j).setCellStyle(csLeft);
    }

    //Fifth Row
    sheet1.addMergedRegion(new CellRangeAddress(4, 4, 0, array.size()));
    sheet1.getRow(4).getCell(0).setCellValue("Results Normalized with Respect to Detectable Concentration");
    sheet1.getRow(4).getCell(0).setCellStyle(csCenter);

    //Rows 6 and beyond. Prints element list and defaults values to 0
    for (int i = 5; i < ElementUtils.skf.length + 5; i++) {
        sheet1.getRow(i).getCell(0).setCellValue(ElementUtils.skf[i - 5]);
        sheet1.getRow(i).getCell(0).setCellStyle(csLeft);
        for (int j = 1; j <= array.size(); j++) {
            sheet1.getRow(i).getCell(j).setCellValue("0.0");
            sheet1.getRow(i).getCell(j).setCellStyle(csRight);
        }
    }

    // Copies values in SampleLibrary array into report
    for (int i = 0; i < array.size(); i++) {
        List<Element> eleArray = array.get(i).getArrayCopy();
        for (int j = 0; j < ElementUtils.skf.length; j++) {
            for (int k = 0; k < eleArray.size(); k++) {

                if (ElementUtils.skf[j].contains(eleArray.get(k).getBaseElement()))
                    sheet1.getRow(j + 5).getCell(i + 1).setCellValue(eleArray.get(k).getConcWeight());
            }

        }
    }
    try {
        wb.write(fileOut);
        wb.close();
        fileOut.close();
    } catch (IOException ex) {
        Logger.getLogger(SampleLibrary.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:eu.alpinweiss.filegen.service.impl.GenerateXlsxFileServiceImpl.java

License:Apache License

public void generateExcel(String excelFilename, int rowCount, List<FieldDefinition> fieldDefinitionList,
        int sheetCount) {

    long startTime = new Date().getTime();

    outputWriterHolder.writeValueInLine("Excel data generation started");

    Workbook wb = new SXSSFWorkbook();

    try {/*from   w w w  .  j  a  va2  s .  c  o m*/
        CellStyle cs = wb.createCellStyle();
        cs.setFillForegroundColor(IndexedColors.LIME.getIndex());
        cs.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        Font f = wb.createFont();
        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        f.setFontHeightInPoints((short) 12);
        cs.setFont(f);

        SXSSFSheet sheet1 = (SXSSFSheet) wb.createSheet("dataSheet");

        int columnCount = fieldDefinitionList.size();

        Map<Integer, Input2TableInfo> input2TableInfoMap = new LinkedHashMap<>(columnCount);

        for (int i = 0; i < columnCount; i++) {
            Input2TableInfo input2TableInfo = new Input2TableInfo();
            FieldDefinition fieldDefinition = fieldDefinitionList.get(i);
            input2TableInfo.setFieldText(fieldDefinition.getFieldName());
            input2TableInfo.setFieldDefinition(fieldDefinition);
            input2TableInfo.initCellStyle(wb);
            input2TableInfo.initGenerator();
            input2TableInfoMap.put(i, input2TableInfo);
        }

        if (sheetCount > 1) {
            CountDownLatch startSignal = new CountDownLatch(1);
            CountDownLatch doneSignal;

            doneSignal = new CountDownLatch(sheetCount);

            ParameterVault parameterVault = new DefaultParameterVault(0, rowCount);
            SheetProcessor stringProcessorSheet1 = new SheetProcessor(parameterVault, startSignal, doneSignal,
                    cs, sheet1, columnCount, input2TableInfoMap, outputWriterHolder);
            new Thread(stringProcessorSheet1, "Processor-" + sheetCount).start();

            for (int i = 0; i < sheetCount - 1; i++) {
                SXSSFSheet sheet = (SXSSFSheet) wb.createSheet("dataSheet_" + i);
                ParameterVault parameterVaultRest = new DefaultParameterVault(i + 1, rowCount);
                SheetProcessor stringProcessor = new SheetProcessor(parameterVaultRest, startSignal, doneSignal,
                        cs, sheet, columnCount, input2TableInfoMap, outputWriterHolder);
                new Thread(stringProcessor, "Processor-" + i).start();
            }

            startSignal.countDown();
            doneSignal.await();
        } else {
            ParameterVault parameterVault = new DefaultParameterVault(0, rowCount);
            new SheetProcessor(outputWriterHolder).generateSheetData(parameterVault, cs, sheet1, columnCount,
                    input2TableInfoMap);
        }

        outputWriterHolder.writeValueInLine("Excel data generation finished.");
        long generationTime = new Date().getTime();
        outputWriterHolder.writeValueInLine("Time used " + ((generationTime - startTime) / 1000) + " sec");
        outputWriterHolder.writeValueInLine("Writing to file.");

        FileOutputStream fileOut = new FileOutputStream(excelFilename.trim());

        wb.write(fileOut);
        fileOut.close();

        long writeTime = new Date().getTime();
        outputWriterHolder.writeValueInLine("Time used " + ((writeTime - generationTime) / 1000) + " sec");
        outputWriterHolder.writeValueInLine("Total time used " + ((writeTime - startTime) / 1000) + " sec");
        outputWriterHolder.writeValueInLine("Done");
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        try {
            wb.close();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

}