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:com.github.xiilei.ecdiff.Processor.java

License:Apache License

public void diff() {
    try {/*www  .ja va2 s. c o  m*/
        logger.info("start ,src:" + job.getSrc() + ",dist:" + job.getDist());
        Store store = this.getStoreFromSrc();
        Workbook wb = readExcelFileByext(job.getDist());
        this.font = wb.createFont();
        this.font.setColor((short) 0xa);
        int rows_len = 0, i = 0, max_cells_len = 0;
        Sheet sheet = wb.getSheetAt(job.getDistSheet());
        rows_len = sheet.getPhysicalNumberOfRows();
        logger.info("Dist,open " + sheet.getSheetName() + " with " + rows_len + " rows");
        for (i = 0; i < rows_len; i++) {
            Row row = sheet.getRow(i);
            max_cells_len = row.getPhysicalNumberOfCells();
            if (!job.checkDistIndex(max_cells_len)) {
                logger.warn("Dist,The length of columns is too small at row " + i + ",length:" + max_cells_len);
                continue;
            }
            if (job.isByrow()) {
                cellComparer(store.get(i), row.getCell(job.getDistColumnIndex()));
            } else {
                cellComparer(store.get(getStringCellValue(row.getCell(job.getDistColumnIdIndex()))),
                        row.getCell(job.getDistColumnIndex()));
            }
        }
        try (FileOutputStream out = new FileOutputStream(job.getOutFileName())) {
            wb.write(out);
        }
        logger.info("output file:" + job.getOutFileName());
    } catch (Exception e) {
        logger.fatal(e.getMessage(), e);
        //                e.printStackTrace();
    }
}

From source file:com.glaf.oa.reports.web.springmvc.OAReportController.java

License:Apache License

public static void exportExcel(String fileName, String targetName, Map<String, Object> datas,
        HttpServletResponse response) {//from  w  ww  .  ja va 2 s .  c o m
    fileName = SystemProperties.getAppPath() + "/WEB-INF/conf/templates/oa/" + fileName + ".xls";
    XLSTransformer transformer = new XLSTransformer();
    FileInputStream fis = null;
    OutputStream os = null;
    Workbook workbook = null;
    try {
        fis = new FileInputStream(fileName);
        workbook = transformer.transformXLS(fis, datas);
        response.reset();
        response.setHeader("content-disposition", "attachment; filename=" + targetName + ".xls");
        response.setContentType("application/msexcel");
        os = response.getOutputStream();
        if (os != null) {
            workbook.write(os);
        }
    } catch (FileNotFoundException e) {
        logger.error("exportExcel:" + e.getMessage());
    } catch (ParsePropertyException e) {
        logger.error("exportExcel:" + e.getMessage());
    } catch (InvalidFormatException e) {
        logger.error("exportExcel:" + e.getMessage());
    } catch (IOException e) {
        logger.error("exportExcel:" + e.getMessage());
    } finally {
        try {
            if (fis != null)
                fis.close();
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            logger.debug("exportExcel:" + e.getMessage());
        }
    }

}

From source file:com.glaf.oa.reports.web.springmvc.OAReportController.java

License:Apache License

private void saveWorkbook(Workbook workBook, HttpServletResponse response, String targetName) {
    OutputStream os = null;/*  w ww .  j  av a  2s.c o m*/
    try {
        response.reset(); // ???
        response.setHeader("content-disposition", "attachment; filename=" + targetName);
        response.setContentType("application/msexcel");
        os = response.getOutputStream();
        if (os != null) {
            workBook.write(os);
        }

    } catch (FileNotFoundException e) {
        logger.error("function saveWorkbook error:" + e.getMessage());
    } catch (IOException e) {
        logger.error("function saveWorkbook error:" + e.getMessage());
    } finally {
        try {
            if (os != null) {
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            logger.error("function saveWorkbook error:" + e.getMessage());
        }

    }

}

From source file:com.glaf.report.jxls.JxlsReportContainer.java

License:Apache License

public byte[] toXls(String reportId, String actorId, Map<String, Object> context) {
    Workbook wb = JxlsReportContainer.getContainer().execute(reportId, actorId, context);
    if (wb != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        try {/*from w ww .  j  ava  2  s.  co m*/
            wb.write(bos);
            bos.flush();
            return baos.toByteArray();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            wb = null;
            try {
                baos.close();
            } catch (IOException e) {
            }
            try {
                bos.close();
            } catch (IOException e) {
            }
            baos = null;
            bos = null;
        }
    }
    return null;
}

From source file:com.glaf.report.web.springmvc.MxReportController.java

License:Apache License

@ResponseBody
@RequestMapping("/xls")
public void xls(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String reportId = request.getParameter("reportId");
    if (StringUtils.isNotEmpty(reportId)) {
        LoginContext loginContext = RequestUtils.getLoginContext(request);

        Map<String, Object> params = RequestUtils.getParameterMap(request);

        java.util.Enumeration<?> e = request.getAttributeNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            params.put(name, request.getAttribute(name));
        }/*from  w w  w  .ja  v a2s  .c o  m*/

        Workbook wb = JxlsReportContainer.getContainer().execute(reportId, loginContext.getActorId(), params);
        if (wb != null) {
            String contentDisposition = "attachment;filename=\"export.xls\"";
            response.setHeader("Content-Transfer-Encoding", "base64");
            response.setHeader("Content-Disposition", contentDisposition);
            response.setContentType("application/octet-stream");
            java.io.OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
            outputStream = null;
            wb = null;
        }
    }
}

From source file:com.globalsight.everest.qachecks.DITAQAChecker.java

License:Apache License

public File runQAChecksAndGenerateReport(long p_taskId) throws Exception {
    Task task = TaskHelper.getTask(p_taskId);
    Company company = CompanyWrapper.getCompanyById(task.getCompanyId());
    if (!company.getEnableDitaChecks()) {
        return null;
    }/*from   w  w  w.j  av  a 2s .  c o m*/

    // Create report
    // Note: as SXSSFWorkbook does not support "RichTextString" to highlight
    // check failed segment, we have to use XSSFWorkbook, this need more
    // memory.
    Workbook workBook = new XSSFWorkbook();
    createReport(workBook, task);

    // Write workbook to file
    File reportDir = DITAQACheckerHelper.getReportFileDir(task);
    // As only store one copy for every task, before generate the new report
    // file, delete old ones if exists.
    FileUtil.deleteFile(reportDir);
    reportDir.mkdirs();

    String fileName = getReportFileName(task);
    File reportFile = new File(reportDir, fileName);
    FileOutputStream out = new FileOutputStream(reportFile);
    workBook.write(out);
    out.close();

    return reportFile;
}

From source file:com.globalsight.everest.qachecks.QAChecker.java

License:Apache License

public String saveReportFile(Workbook p_workbook, Task p_task) throws Exception {
    StringBuilder sb = new StringBuilder();

    sb.append(QACheckerHelper.getQAReportPath(p_task));
    new File(sb.toString()).mkdirs();
    sb.append(QACheckerHelper.getQAReportName(p_task));

    File file = new File(sb.toString());
    FileOutputStream out = new FileOutputStream(file);
    p_workbook.write(out);
    out.close();/*from www .  j ava2  s . c  om*/
    ((SXSSFWorkbook) p_workbook).dispose();

    return sb.toString();
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.reports.CommentXlsReportHelper.java

License:Apache License

/**
 * Generates the Excel report and spits it to the outputstream The report
 * consists of all in progress workflows that are currently at a reviewOnly
 * stage./* w ww .  j  av  a 2s.c o  m*/
 * 
 * @return File
 * @exception Exception
 */
public void generateReport(HttpServletRequest p_request, HttpServletResponse p_response) throws Exception {
    uiLocale = (Locale) p_request.getSession().getAttribute(WebAppConstants.UILOCALE);
    bundle = PageHandler.getBundle(p_request.getSession());
    userId = (String) p_request.getSession(false).getAttribute(WebAppConstants.USER_NAME);
    String companyId = (String) p_request.getSession().getAttribute("current_company_id");
    CompanyThreadLocal.getInstance().setIdValue(companyId);
    // show Priority or not
    setShowPriority(p_request);
    s_logger.debug("showPriority:" + showPriority);
    // show Category or not
    setShowCategory(p_request);
    setStatus(p_request);
    setSourceAndTarget(p_request);

    Workbook p_workbook = new SXSSFWorkbook();
    createSheets(p_request, p_workbook, p_response);

    // Cancelled the report, return nothing.
    if (isCancelled()) {
        p_response.sendError(p_response.SC_NO_CONTENT);
        return;
    }

    ServletOutputStream out = p_response.getOutputStream();
    p_workbook.write(out);
    out.close();
    ((SXSSFWorkbook) p_workbook).dispose();
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.reports.generator.CharacterCountReportGenerator.java

License:Apache License

/**
 * Generates Excel reports/*from  w ww .j  av a 2 s  .co m*/
 * 
 * @param p_jobIDS
 *            Job ID List
 * @param p_targetLocales
 *            Target Locales List
 * @param p_companyName
 *            Company Name
 * @throws Exception
 */
public File[] generateReports(List<Long> p_jobIDS, List<GlobalSightLocale> p_targetLocales) throws Exception {
    if (p_jobIDS == null || p_jobIDS.size() == 0) {
        p_jobIDS = m_jobIDS;
        p_targetLocales = m_targetLocales;
    } else if (m_jobIDS == null || m_jobIDS.size() == 0) {
        m_jobIDS = p_jobIDS;
    }
    List<File> workBooks = new ArrayList<File>();
    int finishedJobNum = 0;
    for (long jobID : p_jobIDS) {
        // Cancel generate reports.
        if (isCancelled())
            return null;

        Job job = ServerProxy.getJobHandler().getJobById(jobID);
        if (job == null)
            continue;
        setAllCellStyleNull();

        File file = ReportHelper.getXLSReportFile(getReportType(), job);
        Workbook workBook = new SXSSFWorkbook();
        createReport(workBook, job, p_targetLocales);

        FileOutputStream out = new FileOutputStream(file);
        workBook.write(out);
        out.close();
        ((SXSSFWorkbook) workBook).dispose();

        // Write total Segment Count
        FileInputStream fis = new FileInputStream(file);
        Workbook workbook = ExcelUtil.getWorkbook(file.getAbsolutePath(), fis);
        List<GlobalSightLocale> jobTL = ReportHelper.getTargetLocals(job);
        for (GlobalSightLocale trgLocale : p_targetLocales) {
            if (!jobTL.contains(trgLocale))
                continue;

            Sheet sheet = ExcelUtil.getSheet(workbook, trgLocale.toString());
            Row row = getRow(sheet, 4);
            Cell cell = getCell(row, 3);
            cell.setCellValue(totalSegmentCount.get(trgLocale.getDisplayName(m_uiLocale)).toString());
        }
        out = new FileOutputStream(file);
        workbook.write(out);
        out.close();
        workBooks.add(file);

        // Sets Reports Percent.
        setPercent(++finishedJobNum);
    }

    return ReportHelper.moveReports(workBooks, m_userId);
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.reports.generator.CommentsAnalysisReportGenerator.java

License:Apache License

/**
 * Generates Excel report/*from  w ww.java2 s  .c  om*/
 * 
 * @param p_jobIDS
 *            Job ID List
 * @param p_targetLocales
 *            Target Locales List
 * @param p_companyName
 *            Company Name
 * @throws Exception
 */
public File[] generateReports(List<Long> p_jobIDS, List<GlobalSightLocale> p_targetLocales) throws Exception {
    ArrayList<String> stateList = ReportHelper.getAllJobStatusList();
    stateList.remove(Job.PENDING);

    if (p_jobIDS == null || p_jobIDS.size() == 0) {
        p_jobIDS = m_jobIDS;
        p_targetLocales = m_targetLocales;
    } else if (m_jobIDS == null || m_jobIDS.size() == 0) {
        m_jobIDS = p_jobIDS;
    }
    List<File> workBooks = new ArrayList<File>();
    String dateFormat = request.getParameter(WebAppConstants.DATE_FORMAT);
    Workbook combinedWorkBook = new SXSSFWorkbook();
    List<Job> jobsList = new ArrayList<Job>();
    Set<String> stateSet = new HashSet<String>();
    Set<String> projectSet = new HashSet<String>();
    if (dateFormat == null) {
        dateFormat = DEFAULT_DATE_FORMAT;
    }

    int finishedJobNum = 0;
    for (long jobID : p_jobIDS) {
        // Cancel generate reports.
        if (isCancelled())
            return null;

        Job job = ServerProxy.getJobHandler().getJobById(jobID);
        if (job == null || !stateList.contains(job.getState()))
            continue;

        stateSet.add(job.getDisplayState());
        projectSet.add(job.getProject().getName());
        if (isCombineAllJobs) {
            jobsList.add(job);
            createReport(combinedWorkBook, job, p_targetLocales, dateFormat);
        } else {
            setAllCellStyleNull();
            Workbook workBook = new SXSSFWorkbook();
            createReport(workBook, job, p_targetLocales, dateFormat);
            File file = getFile(reportType, job, workBook);
            FileOutputStream out = new FileOutputStream(file);
            workBook.write(out);
            out.close();
            ((SXSSFWorkbook) workBook).dispose();
            workBooks.add(file);
        }

        // Sets Reports Percent.
        setPercent(++finishedJobNum);
    }

    if (isCombineAllJobs) {
        File file = getFile(reportType + TAG_COMBINED, null, combinedWorkBook);
        addCriteriaSheet(combinedWorkBook, jobsList, stateSet, projectSet);
        FileOutputStream out = new FileOutputStream(file);
        combinedWorkBook.write(out);
        out.close();
        ((SXSSFWorkbook) combinedWorkBook).dispose();
        workBooks.add(file);
    }

    return ReportHelper.moveReports(workBooks, m_userId);
}