private void jButton3ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton3ActionPerformed String arquivo = "C:/projeto/service/selfservice/relatorio/relRecibo.jasper"; Map<String, Object> map = new HashMap<>(); map.put("VENDA", jtCodigo.getText()); map.put("VALORTOTAL", jtTotalVenda.getText()); map.put("FALTA", jtFalta.getText()); String pago = String.valueOf( Math.abs( Double.parseDouble(jtFalta.getText()) - Double.parseDouble(jtTotalVenda.getText()))); map.put("PAGO", pago); // System.out.println(map); try { JasperReport jasperReport; Connection con; JasperPrint jasperPrint; jasperReport = (JasperReport) JRLoader.loadObject(arquivo); con = DriverManager.getConnection("jdbc:odbc:service", "", ""); jasperPrint = JasperFillManager.fillReport(jasperReport, map, con); JasperViewer jrviewer = new JasperViewer(jasperPrint, false); jrviewer.setVisible(true); } catch (JRException | SQLException ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } } // GEN-LAST:event_jButton3ActionPerformed
public void runReporteVentasPorAnualContado(String fecha) { try { String master = System.getProperty("user.dir") + "/src/ComponenteReportes/ReporteVentasPorAnualContado.jasper"; // System.out.println("master" + master); if (master == null) { System.out.println("no encuentro el archivo de reporte maestro"); System.exit(2); } JasperReport masterReport = null; try { masterReport = (JasperReport) JRLoader.loadObject(master); } catch (JRException e) { System.out.println("error cargando el reporte maestro:" + e.getMessage()); System.exit(3); } Map parametro = new HashMap(); parametro.put("fecha", fecha); JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parametro, cnn); JasperViewer jviewer = new JasperViewer(jasperPrint, false); jviewer.setTitle("REPORTE VENTAS A CONTADO ANUAL"); jviewer.setVisible(true); cnn.close(); } catch (Exception j) { System.out.println("mensaje de error:" + j.getMessage()); } }
@SuppressWarnings("unchecked") public static void main(String[] args) { try { URL url = JasperAB.class .getClassLoader() .getResource("br/com/analiseFornecedores/relatorio/relatorio_controle_1.jasper"); File reportFile = new File(url.getFile()); JasperReport relatorio = (JasperReport) JRLoader.loadObject(reportFile.getPath()); Collection<RelatorioControleVO> lista = new ArrayList<RelatorioControleVO>(); AnaliseRN rn = new AnaliseRN(); Collection<AnaliseVO> analises = new ArrayList<AnaliseVO>(); try { AnaliseVO filtro = new AnaliseVO(); analises = rn.obterPorFiltro(filtro); lista = rn.obterRelatorioControle(analises); } catch (ExecaoRegraNegocio e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(lista); Map<?, ?> param = new HashMap(); JasperPrint jasperPrint = JRFiller.fillReport(relatorio, param, ds); JasperViewer.viewReport(jasperPrint, true); } catch (JRException e) { e.printStackTrace(); } }
@SuppressWarnings({"rawtypes", "unchecked"}) public byte[] gerarRelatorioJasper( String nomeJasper, List<?> dataSource, Map parametros, String tipo) throws JRException, IOException { FacesContext fContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = fContext.getExternalContext(); // Busca o local onde esta o jasper InputStream fis = externalContext.getResourceAsStream(PATH + nomeJasper); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(fis); // Abre a figura e seta o parâmetro do relatório InputStream imgInputStream = this.getClass().getResourceAsStream("/resources/images/logo/" + "fmb.gif"); parametros.put("IMG_BRASAO", imgInputStream); JRDataSource ds = new JRBeanCollectionDataSource(dataSource); byte[] bytes = null; if (tipo.equals("P")) { bytes = this.gerarRelatorioJasperPDF(jasperReport, parametros, ds); } else if (tipo.equals("X")) { bytes = this.gerarRelatorioJasperXLS(jasperReport, parametros, ds); } else if (tipo.equals("D")) { bytes = this.gerarRelatorioJasperDoc(jasperReport, parametros, ds); } return bytes; }
public Map<String, String> getJasperExportParameters() { try { String format = getFormat(); if (JasperReportConstants.FORMAT_XLS.equals(format)) { HttpServletRequest request = ServletActionContext.getRequest(); String reportId = request.getParameter("report"); File targetJasperFile = getTargetJasperFile(reportId); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(targetJasperFile); // 为了方便模板设计和生产环境部署,扩展提供一个PROPERTY_WORKBOOK_TEMPLATE_FILENAME参数 // 如果在模板文件中定义此参数值,框架会用此文件名转换为对应和jasper文件所在同路径的绝对路径去覆盖模板中PROPERTY_WORKBOOK_TEMPLATE参数值 JRPropertiesMap properties = jasperReport.getPropertiesMap(); String xlsWorkbookTemplateFilename = properties.getProperty(PROPERTY_WORKBOOK_TEMPLATE_FILENAME); if (StringUtils.isNotBlank(xlsWorkbookTemplateFilename)) { String xlsWorkbookTemplateFilepath = getWebRootDir() + getRelativeJasperFilePath() + File.separator + xlsWorkbookTemplateFilename; logger.debug( "Overwrite jasper property: {}={}", JRXlsAbstractExporter.PROPERTY_WORKBOOK_TEMPLATE, xlsWorkbookTemplateFilepath); exportParameters.put( JRXlsAbstractExporter.PROPERTY_WORKBOOK_TEMPLATE, xlsWorkbookTemplateFilepath); } } } catch (Exception e) { logger.error(e.getMessage(), e); throw new WebException(e.getMessage(), e); } return exportParameters; }
private void viewReport() throws Exception { Date fromDate = fromDatePicker.getDate(); Date toDate = toDatePicker.getDate(); if (fromDate.after(toDate)) { POSMessageDialog.showError( BackOfficeWindow.getInstance(), com.floreantpos.POSConstants.FROM_DATE_CANNOT_BE_GREATER_THAN_TO_DATE_); return; } fromDate = DateUtil.startOfDay(fromDate); toDate = DateUtil.endOfDay(toDate); ReportService reportService = new ReportService(); MenuUsageReport report = reportService.getMenuUsageReport(fromDate, toDate); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("reportTitle", "========= LAPORAN PENJUALAN PER MENU =========="); map.put("fromDate", ReportService.formatShortDate(fromDate)); map.put("toDate", ReportService.formatShortDate(toDate)); map.put("reportTime", ReportService.formatFullDate(new Date())); JasperReport jasperReport = (JasperReport) JRLoader.loadObject( getClass().getResource("/com/floreantpos/ui/report/menu_usage_report.jasper")); JasperPrint jasperPrint = JasperFillManager.fillReport( jasperReport, map, new JRTableModelDataSource(report.getTableModel())); JRViewer viewer = new JRViewer(jasperPrint); reportContainer.removeAll(); reportContainer.add(viewer); reportContainer.revalidate(); }
public static Object read(Node node, String mappingFile) { Object object = null; InputStream mis = null; try { mis = JRLoader.getLocationInputStream(mappingFile); Mapping mapping = new Mapping(); mapping.loadMapping(new InputSource(mis)); object = read(node, mapping); } catch (JRException e) { throw new JRRuntimeException(e); } finally { if (mis != null) { try { mis.close(); } catch (IOException e) { } } } return object; }
public void informe() { // try - para controlar las excepciones. try { // Iniciamos una transacción st.beginTransaction(); // Obtenemos una lista de funcionario List<Funcionario> lista = (List<Funcionario>) st.createQuery("From Funcionario").list(); // Utilizamos el método siguiente para cargar el reporte "FuncionarioReport.jasper" // El "JRLoader.loadObject" es el cargador. JasperReport report = (JasperReport) JRLoader.loadObject( ClassLoader.getSystemResource("com/informes/FuncionarioReport.jasper")); // El método siguiente nos permite pasarle los datos al reporte utilizando // JRBeanCollectionDataSource y como argumento la lista que creamos más arriba. // La lista posee los siguiente campos: "id" "nombres" "apellidos" "dir" "cargo" en // coincidencia con los de nuestro archivo de reporte. JasperPrint fillReport = JasperFillManager.fillReport(report, null, new JRBeanCollectionDataSource(lista)); // El JasperViewer para visualizar, le pasamos como argumento nuestro "fillReport" de arriba. JasperViewer jviewer = new JasperViewer(fillReport, false); // Le damos un título al reporte. jviewer.setTitle("Lista de Funcionarios"); // La hacemos visible. jviewer.setVisible(true); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error cargando reporte."); } }
protected JasperReport evaluateReport(byte evaluation) throws JRException { JasperReport report = null; JRExpression expression = getExpression(); source = evaluateExpression(expression, evaluation); if (source != null) // FIXME put some default broken image like in browsers { Boolean isUsingCache = getUsingCache(); if (isUsingCache == null) { isUsingCache = source instanceof String; } if (isUsingCache && filler.fillContext.hasLoadedSubreport(source)) { report = filler.fillContext.getLoadedSubreport(source); } else { if (source instanceof net.sf.jasperreports.engine.JasperReport) { report = (JasperReport) source; } else if (source instanceof java.io.InputStream) { report = (JasperReport) JRLoader.loadObject((InputStream) source); } else if (source instanceof java.net.URL) { report = (JasperReport) JRLoader.loadObject((URL) source); } else if (source instanceof java.io.File) { report = (JasperReport) JRLoader.loadObject((File) source); } else if (source instanceof java.lang.String) { report = RepositoryUtil.getReport((String) source); // (JasperReport)JRLoader.loadObjectFromLocation( // (String)source, // filler.reportClassLoader, // filler.urlHandlerFactory, // filler.fileResolver // ); } else { throw new JRRuntimeException( "Unknown subreport source class " + source.getClass().getName()); } if (isUsingCache) { filler.fillContext.registerLoadedSubreport(source, report); } } } return report; }
@SuppressWarnings({"rawtypes", "unchecked"}) protected void procesar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub /*CABECERA DE SALIDA*/ response.setHeader("Content-Disposition", "attachment; filename=\"CronogramaCredito.pdf\";"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("application/pdf"); /*OBTIENE FLUJO DE SALIDA*/ ServletOutputStream outputStream = response.getOutputStream(); /*PARAMETROS*/ Parameters parameters = Parameters.getInstance(); /*SERVICIO DE GENERACION DE REPORTES*/ ReporteJasperServiceImpl jasperServiceImpl = new ReporteJasperServiceImpl(); /*RECUPERA DATOS DE LA SIMULACION EN SESION*/ HttpSession session = request.getSession(true); CreditoCabeceraBO creditoCabeceraBO = (CreditoCabeceraBO) session.getAttribute("creditoCabeceraBO"); CreditoCronogramaBO creditoCronogramaBO = (CreditoCronogramaBO) session.getAttribute("creditoCronogramaBO"); List<Cuota> listaCuotasCredito = (List<Cuota>) session.getAttribute("listaCuotasCredito"); try { /* CARGA PARAMETROS PARA REPORTE JASPER*/ JasperReport reporte = (JasperReport) JRLoader.loadObject( this.getClass() .getClassLoader() .getResourceAsStream(parameters.getKey("REPORTE_CREDITO_PYME"))); /* CARGA PARAMETROS DEL REPORTE*/ Map paramReporte = jasperServiceImpl.getParamReporCredPYME(creditoCabeceraBO, creditoCronogramaBO); /* GENERA REPORTE*/ JRExporter exporterPDF = jasperServiceImpl.getExporterJasper( reporte, paramReporte, new JRBeanCollectionDataSource(listaCuotasCredito)); exporterPDF.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); /*MUESTRA REPORTE EN LINEA*/ exporterPDF.exportReport(); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Este método se encarga de generar el reporte * * @param params diccionario de datos */ public void generarReporte(Map params) { try { nConexion = new NegocioConexion(); reporte = (JasperReport) JRLoader.loadObjectFromFile(ruta); reporteFill = JasperFillManager.fillReport(reporte, params, nConexion.conexion()); visualizarReporteGenerado(); } catch (JRException ex) { System.err.println(ex.getMessage()); } }
public void text() throws JRException { long start = System.currentTimeMillis(); JRTextExporter exporter = new JRTextExporter(); File sourceFile = new File("build/reports/TextReport.jrprint"); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".txt"); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString()); exporter.exportReport(); System.err.println("Text creation time : " + (System.currentTimeMillis() - start)); }
/** * Generates the XML representation of the report design loaded from the specified filename. The * result of this operation is an "UTF-8" encoded XML file having the same name as the report * design, plus the <code>*.jasper.jrxml</code> extension, located in the same directory as the * source file. * * @param sourceFileName source file name containing the report design object * @return XML representation of the report design */ public static String writeReportToXmlFile(String sourceFileName) throws JRException { File sourceFile = new File(sourceFileName); /* We need the report name. */ JRReport report = (JRReport) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), report.getName() + ".jasper.jrxml"); String destFileName = destFile.toString(); writeReportToXmlFile(report, destFileName); return destFileName; }
public JasperReport getReporte() { JasperReport jr = null; try { if (compilado != null) { jr = (JasperReport) JRLoader.loadObject(new ByteArrayInputStream(compilado)); } else { return null; } } catch (JRException e) { log.error(" No se pudo transformar a reporte", e); } return jr; }
@SuppressWarnings({"unchecked", "rawtypes"}) public void gerarRelatorio( String nomeJasper, String attachmentName, List<?> dataSource, Map parametros, String tipo) throws JRException, IOException { FacesContext fContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = fContext.getExternalContext(); // Busca o local onde esta o jasper InputStream fis = externalContext.getResourceAsStream(PATH + nomeJasper); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(fis); HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); // Abre a figura e seta o parâmetro do relatório InputStream imgInputStream = this.getClass().getResourceAsStream("resources/images/logo/" + "fmb.gif"); parametros.put("IMG_BRASAO", imgInputStream); StringBuffer filename = new StringBuffer(attachmentName); JRDataSource ds = new JRBeanCollectionDataSource(dataSource); byte[] bytes = null; if (tipo.equals("P")) { bytes = this.gerarRelatorioJasperPDF(jasperReport, parametros, ds); response.setContentType("application/pdf"); filename.append(".pdf").toString(); response.addHeader("content-disposition", "attachment;filename=" + filename); } else if (tipo.equals("X")) { bytes = this.gerarRelatorioJasperXLS(jasperReport, parametros, ds); response.setContentType("application/vnd.ms-excel"); filename.append(".xls").toString(); response.addHeader("content-disposition", "attachment;filename=" + filename); } else if (tipo.equals("D")) { bytes = this.gerarRelatorioJasperDoc(jasperReport, parametros, ds); response.setContentType("application/rtf"); filename.append(".rtf").toString(); response.addHeader("content-disposition", "attachment;filename=" + filename); } if (bytes != null && bytes.length > 0) { response.setContentLength(bytes.length); ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(bytes, 0, bytes.length); ouputStream.flush(); ouputStream.close(); fContext.responseComplete(); } }
public Map<String, Object> getJasperReportParameters() { Map<String, Object> jasperReportParameters = Maps.newHashMap(); try { HttpServletRequest request = ServletActionContext.getRequest(); String reportId = request.getParameter("report"); File targetJasperFile = getTargetJasperFile(reportId); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(targetJasperFile); // 根据模板定义转换处理传入参数类型 JRParameter[] params = jasperReport.getParameters(); for (Map.Entry<String, Object> val : reportParameters.entrySet()) { String key = val.getKey(); if (val.getValue() == null) { continue; } String[] vals = (String[]) val.getValue(); for (JRParameter param : params) { if (!param.isSystemDefined() && param.isForPrompting()) { String name = param.getName(); Class<?> clazz = param.getValueClass(); if (!name.equals(key)) { continue; } // TODO: 先初步添加集合处理,后续逐步添加数字、日期等类型转换处理 if (Collection.class.isAssignableFrom(clazz)) { // 集合类型参数处理,TODO: 可以考虑进一步添加param.getNestedType()处理 jasperReportParameters.put(key, vals); } else { // 其余情况把参数转换为普通字符串传入 jasperReportParameters.put(val.getKey(), StringUtils.join(vals, ",")); } } } } // 设置一些缺省属性供模板内部使用 jasperReportParameters.put("_RPT_ID", reportId); jasperReportParameters.put("_RPT_FORMAT", this.getFormat()); String url = request.getRequestURL().toString(); logger.debug("Report URL: " + url); jasperReportParameters.put("_RPT_URL", url); } catch (Exception e) { logger.error(e.getMessage(), e); throw new WebException(e.getMessage(), e); } return jasperReportParameters; }
public static void exportToExcel(String jrprintFileName, String excelFileName) throws Exception { long start = System.currentTimeMillis(); File sourceFile = new File(URL + jrprintFileName); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(URL + excelFileName); JRXlsExporter exporter = new JRXlsExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString()); exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); exporter.exportReport(); System.err.println("XLS creation time : " + (System.currentTimeMillis() - start)); System.out.println("成功创建了一个Excel文档"); }
private void export( Collection datas, Map a, String type, String defaultFilename, InputStream is) { // logger.debug("导出判断 The method======= export() start......................."); try { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is); prepareReport(jasperReport, type); JRDataSource ds = new JRBeanCollectionDataSource(datas); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, a, ds); if (PDF_TYPE_AUTO.equals(type)) { exportPdf_auto(jasperPrint, defaultFilename); } } catch (Exception e) { e.printStackTrace(); } }
public void pptx() throws JRException { long start = System.currentTimeMillis(); File sourceFile = new File("build/reports/JRMDbReport.jrprint"); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".pptx"); JRPptxExporter exporter = new JRPptxExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); exporter.exportReport(); System.err.println("PPTX creation time : " + (System.currentTimeMillis() - start)); }
public void docx() throws JRException { long start = System.currentTimeMillis(); File sourceFile = new File(TMP_DIR + ALL_CHARTS_REPORT_JRPRINT); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".docx"); JRDocxExporter exporter = new JRDocxExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); exporter.exportReport(); System.err.println("DOCX creation time : " + (System.currentTimeMillis() - start)); }
public void csv() throws JRException { long start = System.currentTimeMillis(); File sourceFile = new File("build/reports/MarkupReport.jrprint"); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".csv"); JRCsvExporter exporter = new JRCsvExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleWriterExporterOutput(destFile)); exporter.exportReport(); System.err.println("CSV creation time : " + (System.currentTimeMillis() - start)); }
public void jxl() throws JRException { long start = System.currentTimeMillis(); File sourceFile = new File("build/reports/DataSourceReport.jrprint"); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".jxl.xls"); JExcelApiExporter exporter = new JExcelApiExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString()); exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE); exporter.exportReport(); System.err.println("XLS creation time : " + (System.currentTimeMillis() - start)); }
public byte[] gerarRelatorio( List<Object> clAttrsRelatorio, String pathReports, String pathImages, String nomeRelatorio) throws JRException { logger.entering(new Object[0]); Map<String, String> parametros = new HashMap<String, String>(); parametros.put(CAMINHO_RELATORIOS, pathReports); parametros.put(CAMINHO_IMAGENS, pathImages); try { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(pathReports + nomeRelatorio); logger.exiting(new Object[0]); return JasperRunManager.runReportToPdf( jasperReport, parametros, new JRBeanCollectionDataSource(clAttrsRelatorio)); } catch (JRException e) { logger.exception(e.getMessage(), e); throw e; } }
private void viewReport() throws Exception { Date fromDate = fromDatePicker.getDate(); Date toDate = toDatePicker.getDate(); if (fromDate.after(toDate)) { POSMessageDialog.showError( BackOfficeWindow.getInstance(), com.floreantpos.POSConstants.FROM_DATE_CANNOT_BE_GREATER_THAN_TO_DATE_); return; } fromDate = DateUtil.startOfDay(fromDate); toDate = DateUtil.endOfDay(toDate); ReportService reportService = new ReportService(); CreditCardReport report = reportService.getCreditCardReport(fromDate, toDate); HashMap<String, Object> map = new HashMap<String, Object>(); ReportUtil.populateRestaurantProperties(map); map.put( "reportTitle", "========= " + Messages.getString("PosMessage.142").toUpperCase() + " =========="); map.put("fromDate", ReportService.formatShortDate(fromDate)); map.put("toDate", ReportService.formatShortDate(toDate)); map.put("reportTime", ReportService.formatFullDate(new Date())); map.put("salesCount", String.valueOf(report.getTotalSalesCount())); map.put("totalSales", NumberUtil.formatNumber(report.getTotalSales())); map.put("netTips", NumberUtil.formatNumber(report.getNetTips())); map.put("netTipsPaid", NumberUtil.formatNumber(report.getTipsPaid())); map.put("netCharge", NumberUtil.formatNumber(report.getNetCharge())); JasperReport jasperReport = (JasperReport) JRLoader.loadObject( getClass().getResource("/com/floreantpos/ui/report/credit_card_report.jasper")); JasperPrint jasperPrint = JasperFillManager.fillReport( jasperReport, map, new JRTableModelDataSource(report.getTableModel())); JRViewer viewer = new JRViewer(jasperPrint); reportContainer.removeAll(); reportContainer.add(viewer); reportContainer.revalidate(); }
@SuppressWarnings("deprecation") public void xhtml() throws JRException { long start = System.currentTimeMillis(); File sourceFile = new File("build/reports/JRMDbReport.jrprint"); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".x.html"); net.sf.jasperreports.engine.export.JRXhtmlExporter exporter = new net.sf.jasperreports.engine.export.JRXhtmlExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleHtmlExporterOutput(destFile)); exporter.exportReport(); System.err.println("XHTML creation time : " + (System.currentTimeMillis() - start)); }
public void ods() throws JRException { long start = System.currentTimeMillis(); File sourceFile = new File(TMP_DIR + ALL_CHARTS_REPORT_JRPRINT); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".ods"); JROdsExporter exporter = new JROdsExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); SimpleOdsReportConfiguration configuration = new SimpleOdsReportConfiguration(); configuration.setOnePagePerSheet(true); exporter.setConfiguration(configuration); exporter.exportReport(); System.err.println("ODS creation time : " + (System.currentTimeMillis() - start)); }
public void xlsx() throws JRException { long start = System.currentTimeMillis(); File sourceFile = new File("build/reports/JRMDbReport.jrprint"); JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile); File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".xlsx"); JRXlsxExporter exporter = new JRXlsxExporter(); exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration(); configuration.setOnePagePerSheet(false); exporter.setConfiguration(configuration); exporter.exportReport(); System.err.println("XLSX creation time : " + (System.currentTimeMillis() - start)); }
public static void write(Object object, String mappingFile, Writer writer) { InputStream mis = null; try { mis = JRLoader.getLocationInputStream(mappingFile); Mapping mapping = new Mapping(); mapping.loadMapping(new InputSource(mis)); write(object, mapping, writer); } catch (JRException e) { throw new JRRuntimeException(e); } finally { if (mis != null) { try { mis.close(); } catch (IOException e) { } } } }
public void ejecutarReporte(String codigo) { try { cn = Conexion.realizarConexion(); String master = System.getProperty("user.dir") + "\\src\\reportes\\reporteEmpleado.jasper"; System.out.println("master: " + master); if (master == null) { showMessageDialog(null, "No se encontro el archivo", "Error", 0); System.exit(2); } JasperReport masterReport = null; try { masterReport = (JasperReport) JRLoader.loadObject(master); } catch (JRException ex) { showMessageDialog(null, "MasterReport:" + ex.getMessage(), "Error", 0); System.exit(3); } Map parametro = new HashMap(); parametro.put("chr_emplcodigo", codigo); JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parametro, cn); JasperViewer jviewer = new JasperViewer(jasperPrint, false); jviewer.setTitle("Reporte"); jviewer.setVisible(true); } catch (ClassNotFoundException ex) { showMessageDialog(null, ex.getMessage(), "Error", 0); } catch (SQLException ex) { showMessageDialog(null, ex.getMessage(), "Error", 0); } catch (Exception ex) { showMessageDialog(null, ex.getMessage(), "Error", 0); } finally { try { cn.close(); } catch (Exception ex) { showMessageDialog(null, ex.getMessage(), "Error", 0); } } }
/** * 按照类型导出不同格式文件 * * @param datas 数据 * @param type 文件类型 * @param is jasper文件的来源 * @param request * @param response * @param defaultFilename默认的导出文件的名称 */ private static void export( Collection datas, String type, String defaultFilename, InputStream is, HttpServletRequest request, HttpServletResponse response) { logger.debug("导出判断 The method======= export() start......................."); try { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is); prepareReport(jasperReport, type); JRDataSource ds = new JRBeanCollectionDataSource(datas, false); Map parameters = new HashMap(); // parameters.put("wheresql", " and status='3'"); /* parameters.put("wheresql", ""); String diver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@192.168.1.156:1521:orcl"; String username = "******"; String password = "******"; ReportDataSource datasource = new ReportDataSource(); datasource.setDiver(diver); datasource.setUrl(url); datasource.setUsername(username); datasource.setPassword(password); Connection con=getConnection(datasource);*/ JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, ds); if (EXCEL_TYPE.equals(type)) { exportExcel(jasperPrint, defaultFilename, request, response); } else if (PDF_TYPE.equals(type)) { exportPdf(jasperPrint, defaultFilename, request, response); } else if (HTML_TYPE.equals(type)) { exportHtml(jasperPrint, defaultFilename, request, response); } else if (WORD_TYPE.equals(type)) { exportWord(jasperPrint, defaultFilename, request, response); } } catch (Exception e) { e.printStackTrace(); } }