Jasper report to excel

Here is my code but take care with the version implemented.
Notice : Export excel with ireport, for ireport 6.0 , java 7

 Map<String, Object> parametro = new HashMap<String, Object>();
                parametro.put("USUARIO", UConstante.NAME_MINISTERIO_USER);
                parametro.put("RUTA_LOGO", PuenteFile.getRutaFiles(FacesContext.getCurrentInstance(), PuenteFile.RUTA_IMG_LOGO));
                parametro.put("PATH_SYSTEM", rutaFileSystemHD);
                parametro.put("WHERE_DATA", WHERE_REGISTRO);
                parametro.put("WHERE_PROYECTO_USUARIO", WHERE_PROYECTO_USUARIO);
                parametro.put("WHERE_ZONA", WHERE_ZONA);
                parametro.put("NAME_APP", RutaFile.NAME_APP);
                parametro.put("ID_USUARIO", getUsuario().getId());
                parametro.put("ID_PROYECTO", beanProyecto.getId());
                parametro.put("SUBREPORT_DIR", SUBREPORT_DIR);

                System.out.println(">>>>>> PARAMETROS :" + parametro.toString());

              try {
                    JasperPrint jasperPrint = JasperFillManager.fillReport(path, parametro, PgConnector.getConexion());
                    JRXlsExporter xlsExporter = new JRXlsExporter();
                    xlsExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
                    xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(PATH_REPORT_FILE + nameExcel);
                    SimpleXlsReportConfiguration xlsReportConfiguration = new SimpleXlsReportConfiguration();
                    SimpleXlsExporterConfiguration xlsExporterConfiguration = new SimpleXlsExporterConfiguration();
                    xlsReportConfiguration.setOnePagePerSheet(true);
                    xlsReportConfiguration.setRemoveEmptySpaceBetweenRows(false);
                    xlsReportConfiguration.setDetectCellType(true);
                    xlsReportConfiguration.setWhitePageBackground(false);
                    xlsExporter.setConfiguration(xlsReportConfiguration);
                    xlsExporter.exportReport();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }

and for lower versions of ireport 5.6

          try {
                   JasperPrint jasperPrint = JasperFillManager.fillReport(new FileInputStream(path), parametro, PgConnector.getConexion());
                    JRXlsExporter exporterXLS = new JRXlsExporter();
                    exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
                    exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
                    exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
                    exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
                    exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
                    exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_FILE_NAME,PATH_REPORT_FILE + nameExcel);
                    exporterXLS.exportReport();
                } catch (Exception ex) {
                    ex.printStackTrace();

                }

Содержание

  1. How to export to multiple sheets in excel from jasper report
  2. 1 Answer 1
  3. JasperReports — Exporting Reports
  4. Exporting to Other Formats
  5. JasperReports – Экспорт отчетов
  6. Экспорт в другие форматы
  7. How do you export a JasperReport to an Excel file with multiple worksheets?
  8. 3 Answers 3
  9. Jasper report excel export output
  10. 2 Answers 2
  11. Linked
  12. Related
  13. Hot Network Questions
  14. Subscribe to RSS

How to export to multiple sheets in excel from jasper report

I am working on a report with iReport that have many subreports.

I want to have two other sheets in the excel file when generating the report from my application.

When searching the internet I found answers about creating a break in the report, having the option «Ignore pagination » in the subreports «true» , but it is still not clear for me.

What are my options to control how and when a new sheet is created

1 Answer 1

In jasper report there are different ways to achieve new sheet both in jrxml and in java code. The default behavior is to create a new sheet for every page. I will illustrated the 3 most common ways with relative problem in using them.

Ignore pagination and break element

Method

set isIgnorePagination=»true» on the jasperReport tag and add

when you need a new sheet.

Problem: The report will not be beautiful if you export also to pdf (since its ignoring pagination)

Use the jrxml properties

Method To avoid creating new sheet on every new page, set property

And when you want it to create a new sheet before or after an reportElement add relative property:

Problem: The columns on every sheet will be the same and this can result in ugly colspan on different sheet’s

Use java and controll the sheet’s as you like (loading different reports)

Method

Problem: You can not use this method if you are using jasper report server.

Источник

JasperReports — Exporting Reports

We have seen in the previous chapter, how to print and view a JasperReport generated document. Here, we shall see how to transform or export these reports into other formats such as PDF, HTML, and XLS. Facade class net.sf.jasperreports.engine.JasperExportManager is provided to achieve this functionality. Exporting means transforming the JasperPrint object (.jrprint file) into different format.

The following code (JasperReportExport.java) demonstrates the exporting process of the JasperReport document. The JasperExportManager provides methods to export a report into PDF, HTML, and XML only. To export to the XLS format, we have used the class net.sf.jasperreports.engine.export.JRXlsExporter. This code generates following three files −

  • sample_report.pdf
  • sample_report.html
  • sample_report.xls

Exporting to Other Formats

Let’s write a report template. The contents of the JRXML file (C:toolsjasperreports-5.0.1testjasper_report_template.jrxml) are as below −

Next, contents of the POJO file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBean.java are as given below −

The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList.java are as given below −

Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint.

Here, we have included the logic to export the jasper print file to pdf, html and xls format.

Источник

JasperReports – Экспорт отчетов

В предыдущей главе мы видели, как распечатать и просмотреть документ, сгенерированный JasperReport. Здесь мы увидим, как преобразовать или экспортировать эти отчеты в другие форматы, такие как PDF, HTML и XLS. Класс фасада net.sf.jasperreports.engine.JasperExportManager предоставляется для достижения этой функциональности. Экспорт означает преобразование объекта JasperPrint (файл .jrprint) в другой формат.

Следующий код (JasperReportExport.java) демонстрирует процесс экспорта документа JasperReport. JasperExportManager предоставляет методы для экспорта отчета только в PDF, HTML и XML. Для экспорта в формат XLS мы использовали класс net.sf.jasperreports.engine.export.JRXlsExporter . Этот код генерирует следующие три файла –

  • sample_report.pdf
  • sample_report.html
  • sample_report.xls

Экспорт в другие форматы

Давайте напишем шаблон отчета. Содержимое файла JRXML (C: tools jasperreports-5.0.1 test jasper_report_template.jrxml) приведено ниже:

Далее содержимое файла POJO C: tools jasperreports-5.0.1 test src com tutorialspoint DataBean.java указано ниже –

Содержимое файла C: tools jasperreports-5.0.1 test src com tutorialspoint DataBeanList.java указано ниже –

Напишите файл основного класса JasperReportFill.java , который получает коллекцию Java-бинов из класса (DataBeanList) и передает ее в механизм JasperReports, чтобы заполнить шаблон отчета. Сохраните его в каталоге C: tools jasperreports-5.0.1 test src com tutorialspoint .

Здесь мы включили логику для экспорта файла печати jasper в формат pdf, html и xls.

Источник

How do you export a JasperReport to an Excel file with multiple worksheets?

We have a report that the customer would like to have exported to an excel format where it has multiple worksheets. Essentially the two queries share the same parameters, but everything else is different.

In jasper-reports how do you export to an excel file with multiple worksheets (ideally from different data sources)?

3 Answers 3

Thanks to this thread it really was easier for me to create an Excel export with multiple sheets. What I found out was that you could use the following:

and the exporter will automatically use every JasperPrint object to construct each sheet; also the name of the Jasper report (as specified in the jrxml file) is used as the name of each sheet.

Currently this solution works on my local project, so I just wanted to let you know.

Thanks to belisarius link we seem to have figured it out. The basics of how to do it is create your JasperPrint objects for each sheet as you normally would. So you have:

The JasperPrint objects are already filled with the datasource at this point. Then you do:

What this does it sets i to the number of pages currently in the firstWorkSheet (which should be one). Then it loops thourgh the pages in the secondWorkSheet and adds them to the firstWorkSheet.

Make sure in you jasperReport you have it set to print as one page for each of the work sheet jrxml files and you should be good to go. I will come update this if anything changes, but this should work.

UPDATE:

Discovered you need to use net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter

as there seems to be an issue when exporting to multiple work sheets.

Also the setting in the jrxml file for isIgnorePagination needs to be:

so that each jrxml file is exported as a single page.

Источник

Jasper report excel export output

I have total 5 reports in 5 different files and i want to make only single excel file which contains these five reports and five different sheets how it will be possible with jasper report?

Thanks in advance

2 Answers 2

Instead of creating 5 reports just use one report and set the property net.sf.jasperreports.export.xls.one.page.per.sheet to true .

Then just rename them with net.sf.jasperreports.export.xls.sheet.name and use the Page Break element

Search on the internet for more information if needed. There are actually a lot of examples for this.

First you have to create JasperPrint objects for each sheet as you normally would.

Now JasperPrint already have the datasource at this point. Use the Arraylist to add the JasperPrint object and the exporter will use each object to create a sheet

And you need to use net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter as import

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43325

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Aspose.Cells for JasperReports является гибким расширением для JasperReports и JasperServer, предназначенным для выгрузки отчетов в форматы Microsoft Excel Workbooks XLS, XLSX, PDF, ODS, TXT и SpreadsheetML без использования Microsoft Excel. Он работает в качестве альтернативы оригинальному ПО для выгрузки Microsoft Excel в формат JasperReports с несколькими наиболее востребованными улучшениями и дополнениями. А также исключает зависимость от библиотеки POI при выгрузке, с высокой степению точности отчетов и при конвертировании в формат таблиц Microsoft Excel.

  • С первого взгляда
  • Платформонезависимость
  • Поддериваемые файловые форматы

С первого взгляда

Обзор возможностей Aspose.Cells for JasperReports.

 Простая установка

 Высокоточное отображение дизайна отчета

 Редактируемые графики

Выгрузка в форматы Excel

Excel Exporter for JasperReports

Aspose.Cells

Платформонезависимость

Aspose.Cells for JasperReports поддрживает J2SE, JasperReports и JasperServer.

 J2SE 5.0 или новее

 JasperReports 2.0 или новее

 JasperServer 2.0 или новее

 JasperReports Spreadsheet Exporter

Aspose.Cells

Поддерживаемые файловые форматы

Aspose.Cells for JasperReports позволяет вам выгружать отчеты напрямую в таблицы Microsoft Excel и OpenOffice (XLS, XLSX, ODS, SpreadsheetML), текстовый и PDF форматы.

  Только вывод
  • Microsoft Excel: XLS, XLSX
  • OpenOffice: ODS
  • SpreadsheetML: XML
  • Вывод с фиксированным макетом: PDF
  • Текст: CSV, Tab-Delimited

Report Converter for JasperReports

Aspose.Cells

Предыдущий Следующий

Создавать отчеты в виде таблиц Microsoft Excel

Печатать отчеты в виде таблиц Microsoft Excel

Экспортировать файлы Excel как редактируемые таблицы. 

Развертывать легко и быстро

Aspose.Cells for JasperReports написана целиком на Java и предоставляется как единичный JAR файл, который может быть легко установлен на машине, где уже работает JasperReports или JasperServer. Установка Aspose.Cells for JasperReports проста — скопирйте Aspose.Cells for JasperReports JAR фал в соответствующий каталог и все.

Соответствие дизайна конструктору отчетов

Aspose.Cells for JasperReports выгружает отчеты в поддерживаемые форматы с высокой степенью точности так, что может показаться, что отчет был выгружен с использованием функции выгрузки нативного приложения JasperReports.

Редактируемые таблицы Excel

Aspose.Cells for JasperReports выгружает файлы Excel в виде полностью редактируемых таблиц. Он поддерживает графику Microsoft Excel и любые графики, экспортируемые через Aspose — движок рендеринга преобразует в полностью редактируемые графики, а не в статические картинки, что привело бы к необходимости для конечного пользователя в ручном режиме обрабатывать графику в Microsoft Excel.

Автоматизация Microsoft Office больше не нужна

Aspose.Cells for JasperReports создан с использованием управляемого кода, который никогда не требует установленного на компьютере Microsoft Excel для того, чтобы обрабатывать документы форматов Excel. Это является прекрасной альтернативой автоматизации Microsoft Excel в терминах поддерживаемых возможностей, функций, безопасности, стабильности, масштабируемости, скорости и цены.

Aspose.Cells предлагает индивидуальные наборы API для работы с документами Excel и на других популярных платформах и средах разработки, перечисленных ниже:

This Post will explain , How to export different formats using Jasper and Jrxml using java

Step 1: Download Download Jasper Studio
or I Report Designer

Step 2 : Design your page by providing connection details and query details and what columns needs to be display in PDF/excel/CSV

Step 3: Your design Page details can be mentioned in Summary Band.





 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
  
  
   
  
  
   
   
  
  
   
   
  
  
   
   
  
  
   
   
  
  
   
  
  
   
  
  
   
  
  
   
  
 
 
  
 
 
  
  
 
 
  
  
 
 
  
  
 
 
  
  
 
 
  
   
   
    
     
     
     
     
     
    
    
     
      
     
     
      
      
      
       
        
        
       
      
      
      
       
        
        
       
      
     
     
      
      
      
       
        
        
       
      
      
      
       
        
        
       
      
     
     
      
      
      
       
        
        
       
      
      
      
       
        
        
       
      
     
     
      
      
      
       
        
        
       
      
      
      
       
        
        
       
      
     
    
   
  
 



Step 4: Once design completes , then it is time to write java class to export into different formats

Step 5: Excel report Generation




package arrayListTest;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.export.SimpleCsvExporterConfiguration;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsReportConfiguration;

public class GenerateMultipleReportsFromJasper {
 
  public static void main(String[] args) {

  //Jrxml file source
  String sourceFileName = "C:\Users\Siva\JaspersoftWorkspace\csvpdf\csv_export.jrxml";
  //destination file location
  String outXlsName = "C:\Users\Siva\JaspersoftWorkspace\csvpdf\test.xls";
  //If we want to pass any parameters to jasper report, then we can use this map
  HashMap xlsParams = new HashMap();
  Connection con = null;
  try {
    Class.forName("com.mysql.jdbc.Driver");
    // here employee is database name, root is username and password
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root");
    JasperReport report = JasperCompileManager.compileReport(sourceFileName );
    JasperPrint xlsPrint = JasperFillManager.fillReport(report, xlsParams, con);
    JRXlsExporter xlsExporter = new JRXlsExporter();
    xlsExporter.setExporterInput(new SimpleExporterInput(xlsPrint));
    xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outXlsName));
    SimpleXlsReportConfiguration xlsReportConfiguration = new SimpleXlsReportConfiguration();
    xlsReportConfiguration.setOnePagePerSheet(false);
    xlsReportConfiguration.setRemoveEmptySpaceBetweenRows(true);
    xlsReportConfiguration.setDetectCellType(false);
    xlsReportConfiguration.setWhitePageBackground(false);
    xlsExporter.setConfiguration(xlsReportConfiguration);
    xlsExporter.exportReport();
  } catch (Exception e) {
      System.out.println(e);
    }
    finally{
      try{
 if(con != null){
    con.close();
 }
 
      }
    catch(Exception ex){
 }
    }
  }

}


Step 6: CSV Generation



HashMap csvParamsMap = new HashMap();
String outcsvName = "C:\Users\Siva\JaspersoftWorkspace\csvpdf\test.csv";
JasperReport report1 = JasperCompileManager.compileReport(sourceFileName );
JasperPrint jasperPrint = JasperFillManager.fillReport(report1, csvParamsMap, con);
JRCsvExporter exporter = new JRCsvExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(new File(outcsvName)));
SimpleCsvExporterConfiguration configuration = new SimpleCsvExporterConfiguration();
configuration.setWriteBOM(Boolean.TRUE);
configuration.setRecordDelimiter("rn");
exporter.setConfiguration(configuration);
exporter.exportReport();

Step 7: PDF Generation



HashMap pdfParamsMap = new HashMap();
String outPdfName = "C:\Users\Siva\JaspersoftWorkspace\csvpdf\test.pdf";
JasperReport report2 = JasperCompileManager.compileReport(sourceFileName );
JasperPrint jasperPrint2 = JasperFillManager.fillReport(report2, pdfParamsMap, con);
JRPdfExporter pdfExporter = new JRPdfExporter();
pdfExporter.setExporterInput(new SimpleExporterInput(jasperPrint2));
pdfExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outPdfName));
SimplePdfExporterConfiguration pdfConfiguration = new SimplePdfExporterConfiguration();
pdfConfiguration.setCreatingBatchModeBookmarks(true);
pdfExporter.setConfiguration(pdfConfiguration);

Step 8: Required jar file to execute this program

1. Itext 2.1.7.jar
2. commons-beanutils-1.9.2.jar
3. commons-logging-1.2.jar
4. commons-collections-3.2.1.jar
5. commons-lang-2.6.jar
6. commons-digester-1.6.jar
7. jasperreports-6.2.0.jar
8. mysql-connector-java-5.1.40.jar
9. poi-ooxml-3.16.jar
10. poi-3.12.jar

Step 9: Once We downloaded all jars then add into java build path.

Step 10: This is how we can export different format using jasper jrxml and Java.

If all you want to do is grab a subset of an array, and you already know the positions of the elements you want, you can just use INDEX with an array for the index argument. That is:

=INDEX({11,22,33,44,55},{2,3,5})

returns {22,33,55}. But that’s usually not very useful because you don’t know the positions, and I don’t know any way to get them without a UDF.

What I have done for this kind of in-worksheet array filtration is to write a UDF with the following form:

'Filters an input sequence based on a second "comb" sequence.
'Non-False-equivalent, non-error values in the comb represent the positions of elements
'to be kept.
Public Function combSeq(seqToComb, seqOfCombValues)

    'various library calls to work with 1xn or nx1 arrays or ranges as well as 1-D arrays

    'iterate the "comb" and collect positions of keeper elements

    'create a new array of the right length and copy in the keeper elements

End Function

I only posted pseudocode because my actual code is all calls to library functions, including the collect-positions and copy-from-positions operations. It would probably obscure the basic idea, which is pretty simple.

You’d call such a UDF like so:

=combSeq({23, "", 34, 46, "", "16"}, {23, "", 34, 46, "", "16"} <> "")

or

=combSeq(Q1:Q42, SIN(Z1:Z42) > 0.5)

and use Excel’s normal array mechanics to generate the «comb». It’s a lightweight, Excel-friendly way to get a lot of the benefits of the more standard filter(list-to-filter, test-function) function you might see in other programming systems.

I use the name «comb» because «filter» usually means «filter with this function», and with Excel you have to apply the test function before calling the filtration function. Also it can be useful to compute one «comb» as an intermediate result and then use it to…er, comb…multiple lists.


We have seen in the previous chapter, how to print and view a JasperReport generated document. Here, we shall see how to transform or export these reports into other formats such as PDF, HTML, and XLS. Facade class net.sf.jasperreports.engine.JasperExportManager is provided to achieve this functionality. Exporting means transforming the JasperPrint object (.jrprint file) into different format.

The following code (JasperReportExport.java) demonstrates the exporting process of the JasperReport document. The JasperExportManager provides methods to export a report into PDF, HTML, and XML only. To export to the XLS format, we have used the class net.sf.jasperreports.engine.export.JRXlsExporter. This code generates following three files −

  • sample_report.pdf
  • sample_report.html
  • sample_report.xls

Exporting to Other Formats

Let’s write a report template. The contents of the JRXML file (C:toolsjasperreports-5.0.1testjasper_report_template.jrxml) are as below −

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
   "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports
   http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
   name = "jasper_report_template" language = "groovy" pageWidth = "595"
   pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20"
   topMargin = "20" bottomMargin = "20">

   <queryString>
      <![CDATA[]]>
   </queryString>
   
   <field name = "country" class = "java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>
   
   <field name = "name" class = "java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>
   
   <columnHeader>
      <band height = "23">
         
         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "3" 
               width = "535" height = "15" backcolor = "#70A9A9" />
            
            <box>
               <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
            </box>
            
            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>
         
         <staticText>
            <reportElement x = "414" y = "3" width = "121" height = "15" />
            
            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>
            
            <text><![CDATA[Country]]></text>
         </staticText>
         
         <staticText>
            <reportElement x = "0" y = "3" width = "136" height = "15" />
            
            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font isBold = "true" />
            </textElement>
            
            <text><![CDATA[Name]]></text>
         </staticText>
      
      </band>
   </columnHeader>

   <detail>
      <band height = "16">
         
         <staticText>
            <reportElement mode = "Opaque" x = "0" y = "0" 
               width = "535" height = "14" backcolor = "#E5ECF9" />
            
            <box>
               <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
            </box>
            
            <textElement />
            <text><![CDATA[]]> </text>
         </staticText>
         
         <textField>
            <reportElement x = "414" y = "0" width = "121" height = "15" />
            
            <textElement textAlignment = "Center" verticalAlignment = "Middle">
               <font size = "9" />
            </textElement>
            
            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{country}]]>
            </textFieldExpression>
         </textField>
         
         <textField>
            <reportElement x = "0" y = "0" width = "136" height = "15" />
            <textElement textAlignment = "Center" verticalAlignment = "Middle" />
               
            <textFieldExpression class = "java.lang.String">
               <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>
      
      </band>
   </detail>
	
</jasperReport>

Next, contents of the POJO file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBean.java are as given below −

package com.tutorialspoint;

public class DataBean {
   private String name;
   private String country;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public String getCountry() {
      return country;
   }

   public void setCountry(String country) {
      this.country = country;
   }
}

The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList.java are as given below −

package com.tutorialspoint;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));

      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);
      
      return dataBean;
   }
}

Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName = "c://tools/jasperreports-5.0.1/"
         + "test/jasper_report_template.jasper";
      String printFileName = null;
      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();
      JRBeanCollectionDataSource beanColDataSource =
         new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      try {
         printFileName = JasperFillManager.fillReportToFile(sourceFileName,
            parameters, beanColDataSource);
         if (printFileName != null) {
            /**
             * 1- export to PDF
             */
            JasperExportManager.exportReportToPdfFile(printFileName,
               "C://sample_report.pdf");

            /**
             * 2- export to HTML
             */
            JasperExportManager.exportReportToHtmlFile(printFileName,
               "C://sample_report.html");

            /**
             * 3- export to Excel sheet
             */
            JRXlsExporter exporter = new JRXlsExporter();

            exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME,
               printFileName);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
               "C://sample_report.xls");

            exporter.exportReport();
         }
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

Here, we have included the logic to export the jasper print file to pdf, html and xls format.

Generating Reports

Let’s compile and execute above files using our regular ANT build process. The build.xml file is as given below −

<?xml version = "1.0" encoding = "UTF-8"?>
<project name = "JasperReportTest" default = "executereport" basedir = ".">
   <import file = "baseBuild.xml"/>

   <target name = "executereport" depends = "compile,compilereportdesing,run">
      <echo message = "Im here"/>
   </target>
   
   <target name = "compilereportdesing" description = "Compiles the JXML file and
      produces the .jasper file.">
      
      <taskdef name = "jrc"
         classname = "net.sf.jasperreports.ant.JRAntCompileTask">
         <classpath refid = "classpath" />
      </taskdef>
      
      <jrc destdir = ".">
         <src>
            <fileset dir = ".">
               <include name = "*.jrxml" />
            </fileset>
         </src>
         <classpath refid = "classpath" />
      </jrc>
   
   </target>
	
</project>

Go to the command prompt and then go to the directory C:toolsjasperreports-5.0.1test, where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill. The output is as follows −

C:toolsjasperreports-5.0.1test>ant -Dmain-class=com.tutorialspoint.JasperReportFill
Buildfile: C:toolsjasperreports-5.0.1testbuild.xml

clean-sample:
   [delete] Deleting directory C:toolsjasperreports-5.0.1testclasses
   [delete] Deleting: C:toolsjasperreports-5.0.1testjasper_report_template.jasper
   [delete] Deleting: C:toolsjasperreports-5.0.1testjasper_report_template.jrprint

compile:
   [mkdir] Created dir: C:toolsjasperreports-5.0.1testclasses
   [javac] C:toolsjasperreports-5.0.1testbaseBuild.xml:28:
   warning: 'includeantruntime' was not set, defaulting t
   [javac] Compiling 4 source files to C:toolsjasperreports-5.0.1testclasses

compilereportdesing:
   [jrc] Compiling 1 report design files.
   [jrc] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).
   [jrc] log4j:WARN Please initialize the log4j system properly.
   [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
   [jrc] File : C:toolsjasperreports-5.0.1testjasper_report_template.jrxml ... OK.

run:
   [echo] Runnin class : com.tutorialspoint.JasperReportFill
   [java] log4j:WARN No appenders could be found for logger
   (net.sf.jasperreports.extensions.ExtensionsEnvironment).
   [java] log4j:WARN Please initialize the log4j system properly.

executereport:
   [echo] Im here

BUILD SUCCESSFUL
Total time: 32 seconds

As the result of above execution, you will find three files sample_report.pdf, sample_report.html, sample_report.xls generated in the C: directory.

Introduction

Jaspersoft’s Jasper reports are popular in Java world since they offer a simple way to design templates and export data into many formats — HTML, PDF, DOCX, XLS, XLSX, CSV, ODT, RTF and ODS.

In this simple tutorial, we’ll show how to create a Jasper Excel xlsx report using Java Beans and JRBeanCollectionDataSource and download this report over the REST service using HttpServletResponse. We’ll create one simple bean with two attributes — name and color and use it to fill our basic report that will have only these two fields and belonging labels.

Implementation

Our design will look like this (complete .jrxml file could be found at the end of this tutorial):

Create and download Jasper report xlsx via REST service in Spring Boot

Dependencies

Let’s add Jasper Reports Maven dependency to your pom.xml: 

<dependency>
  <groupId>net.sf.jasperreports</groupId>
  <artifactId>jasperreports</artifactId>
  <version>6.13.0</version>
</dependency>

Implementation

In this example, we’ll have two classes — first is Java Bean that we’ll use as a data source and the second one is an example code where we’ll create xlsx file using our Jasper file and provided data source. 

So, this would be the bean class — it contains only fields and getters and setters.

public class SampleBean {
	
String name;
String color;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}

And this is the exporter class.

package com.javahowtos.jasperdemo.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javahowtos.jasperdemo.beans.SampleBean;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;

@RestController
@RequestMapping("api/document")
public class JasperDemoController {

    @GetMapping()
    public void getDocument(HttpServletResponse response) throws IOException, JRException {

        String sourceFileName = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "SampleJasperReport.jasper")
            .getAbsolutePath();
        List<SampleBean> dataList = new ArrayList<SampleBean>();
        SampleBean sampleBean = new SampleBean();
        sampleBean.setName("some name");
        sampleBean.setColor("red");
        dataList.add(sampleBean);
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
        Map<String, Object> parameters = new HashMap();
        JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);
        JRXlsxExporter exporter = new JRXlsxExporter();
        SimpleXlsxReportConfiguration reportConfigXLS = new SimpleXlsxReportConfiguration();
        reportConfigXLS.setSheetNames(new String[] { "sheet1" });
        exporter.setConfiguration(reportConfigXLS);
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        response.setHeader("Content-Disposition", "attachment;filename=jasperReport.xlsx");
        response.setContentType("application/octet-stream");
        exporter.exportReport();
    }
}

Explanation 

We’ll need the location of our .jasper file that is placed in the resources folder of our Maven project, so we’ll use ResourceUtils to get to the files’ absolute path.

String sourceFileName = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "SampleJasperTemplate.jasper").getAbsolutePath();

The following part of code is just for building up the list of beans that will be provided as a data source to JRBeanCollectionDataSource. In case you don’t want to pass a list of objects, but the only one instead, create it and add it to the list, Jasper will know how to deal with it. 

// creating our list of beans
List<SampleBean> dataList = new ArrayList<SampleBean>();
SampleBean sampleBean = new SampleBean();
sampleBean.setName("some name");
sampleBean.setColor("red");
dataList.add(sampleBean);
// creating datasource from bean list
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);

The parameter Map is used for providing the report with some extra parameters. We currently don’t need that, so we’ll just pass the empty one.

JasperPrint object we create in the following line will be later used to fill the report that will be written to HttpServletResponse’s output stream:

Map<String, Object> parameters = new HashMap();
JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);

The following code is used for creating the exporter. Class SmpleXlsxReportConfiguration is used to configure resulting .xlsx file. In this example, we’ll set the sheet name.

  JRXlsxExporter exporter = new JRXlsxExporter();
        SimpleXlsxReportConfiguration reportConfigXLS = new SimpleXlsxReportConfiguration();
        reportConfigXLS.setSheetNames(new String[] { "sheet1" });
        exporter.setConfiguration(reportConfigXLS);
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        response.setHeader("Content-Disposition", "attachment;filename=jasperReport.xlsx");
        response.setContentType("application/octet-stream");
        exporter.exportReport();

It’s important to give the resulting file the name and type so the browser can handle it easily (if you’re using Postman to test this, click Send and Download instead just Send).

Create and download Jasper report xlsx via REST service in Spring Boot

A complete example with JRXML can be found on GitHub.

Conclusion

In this tutorial, we saw how to export xlsx file using Jasper reports and download it via REST service in Spring Boot. You can find a complete list of dependencies in the full project on GitHub. 


Check also…


  • Read HTTP Headers in Spring REST Controller


  • Get health, readiness and liveness information from within an application code


  • Difference Between Request Scope and Session Scope in Spring


  • The Spring Bean Scopes Explained

This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0

This website is not affiliated with Stack Overflow

logo rip

SUPPORT & PARTNERS

  • Advertise with us
  • Contact us
  • Privacy Policy

STAY CONNECTED

Get monthly updates about new articles, cheatsheets, and tricks.

Понравилась статья? Поделить с друзьями:
  • Japanese words with english word
  • Japanese word zen means
  • Japanese word with sounds
  • Japanese word with meanings
  • Japanese word of the year