Jasperreports export 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();

                }


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.

В предыдущей главе мы видели, как распечатать и просмотреть документ, сгенерированный 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) приведено ниже:

<?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>

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

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;
   }
}

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

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;
   }
}

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

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();
      }
   }
}

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

Генерация отчетов

Давайте скомпилируем и выполним вышеуказанные файлы, используя наш обычный процесс сборки ANT. Файл build.xml как показано ниже –

<?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>

Перейдите в командную строку и перейдите в каталог C: tools jasperreports-5.0.1 test, где находится файл build.xml. Наконец, выполните команду ant -Dmain-class = com.tutorialspoint.JasperReportFill . Выход выглядит следующим образом –

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

В результате выполнения выше вы найдете три файла sample_report.pdf, sample_report.html, sample_report.xls, сгенерированные в каталоге C: .

Содержание

  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.

Источник

In Main Report, Report properties, Page Format (for this one example report I am looking at), my Page Format has the following properties:

  • Format: Letter is what I always use
  • Width: When I have a report that does both PDF and Excel, the the width is 792.
  • Height: When I have report that does both PDF and Excel, then the height is 612
    Note: Excel doesn’t care what your margins here are. PDF likes these just fine.
  • Units: pixel. Much easier to work in than inches
  • Page Orientation: Landscape
  • Margins: 36 for all margins.

Also, in Report properties, I have made these selections:

  • When No Data Type: No Data Section
  • Summary On A New Page: checked
  • Summary with Page Header and Footer: checked –I could have this unchecked, and in the Summary section, I would have to add the report name and the company logo.
  • Ignore Pagination: After much experiementation, I have decided that unchecked is best, otherwise when doing a PDF or Excel format report, the PDF does not page properly, and can’t be recovered from. It is the lessor of two evils (until Jaspersoft fixes this in a new version).

Also, in the Main Report Properties, in Advanced, Properties, I have added these (which end up near the top of the Source XML):

<property name = "net.sf.jasperreports.export.xls.one.page.per.sheet" value="true"/>

Without the above, JS only puts as many data rows on a single tab as fit within the Page Height.

<property name="net.sf.jasperreports.export.xls.remove.empty.space.between.rows" value="true"/>

The above gets rid of one row with a very large row height at the end of the data tab. Don’t understand why that one very high row is created, but this is needed to get rid of it. Of course having this means that you can’t (easily) have row spacing in the footnotes.

<property name="net.sf.jasperreports.export.xls.remove.empty.space.between.columns" value="true"/>

The above gets rid of empty columns, such as caused by margins, or by poor layout.

<property name="net.sf.jasperreports.export.xls.white.page.background" value="false"/>

The above shows the Excel grid lines, otherwise you get solid white, which kind of ruins the look of Excel (for a data dump).

<property name="net.sf.jasperreports.export.xls.detect.cell.type" value="true"/>

The above tells Excel to treat dates as dates, numbers as numbers, instead of all being treated as text when it is set to “false” (which is the default).
Note: Java’s custom date formats are different from Excel’s custom date formats, so a date format might look good in Excel but bad in Java/HTML, or vis-a-versa, so take care with custom date formats.

<property name="net.sf.jasperreports.export.xls.ignore.graphics" value="false"/>

The above tells Excel to not delete the company logo graphic. “true” (which is the default) deletes graphics.

<property name="net.sf.jasperreports.page.break.no.pagination" value="apply"/>

The above, as far as I know, has to be typed or cut-n-pasted directly into the Source XML. I have not found a place to select it under any Properties. I am not certain why it is needed, but it is.

<property name="net.sf.jasperreports.export.xls.sheet.names.all" value="Data/Footnotes"/>

The above tells Excel, to name the first tab “Data”, and the second tab “Footnotes”. Instead of “Data”, I would recommend something more descriptive, maybe the report name.

<property name="net.sf.jasperreports.export.xls.freeze.row" value="3"/>

The above tells Excel to freeze the top 2 rows. Once in Excel therefore, the report name/company logo row, and the column headers row is frozen, and the user can scroll through thousands of records and still see them. Without this, the user would have had to do it themselves.

<property name="net.sf.jasperreports.print.keep.full.text" value="true"/>

The above keeps JS from truncating values wider than the explicity set colunmn widths. In Excel this is seen as wrapping.

<property name="net.sf.jasperreports.exports.xls.font.size.fix.enabled" value="false"/>

The above keeps JS from reducing the font size by 1 when exporting to Excel. For example, without this, an Arial 10 in Studio, in Server when exported to Excel ends up as an Arial 9 font.


The following Report Export properties are used by the exporters to create default exporter filter instances that filter out content based on element origin information:

net.sf.jasperreports.export.{format}.exclude.origin.{suffix}.{arbitrary_name}
net.sf.jasperreports.export.{format}.exclude.origin.keep.first.{suffix}.{arbitrary_name}

Where:

  • {format} is one of pdf, html, xls, rtf, odt, csv, txt
  • {suffix} is one of band, group, report

[source|source]

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.

With Java

Export to xlsx format

try (InputStream inputStream = JRLoader.getResourceInputStream(path)) {  // read report as input stream 
    JasperReport  jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream)); // compile report

    Map<String, Object> params = new HashMap<>(); // init map with report's parameters
    params.put(JRParameter.REPORT_LOCALE, Locale.US);
    params.put(JRParameter.IS_IGNORE_PAGINATION, true);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, connection);  // prepare report - passs parameters and jdbc connection

    JRXlsxExporter exporter = new JRXlsxExporter(); // initialize exporter 
    exporter.setExporterInput(new SimpleExporterInput(jasperPrint)); // set compiled report as input
    exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile));  // set output file via path with filename
    SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
    configuration.setOnePagePerSheet(true); // setup configuration
    configuration.setDetectCellType(true);
    exporter.setConfiguration(configuration); // set configuration
    exporter.exportReport();
}

Adding autofilter for columns

The using of net.sf.jasperreports.export.xls.auto.filter property allow to add autofilter in generated xls file.

<columnHeader>
    <band height="30" splitType="Stretch">
        <staticText>
            <reportElement x="0" y="0" width="100" height="20">
                <property name="net.sf.jasperreports.export.xls.auto.filter" value="Start"/>
            </reportElement>
            <text><![CDATA[First column with filter]]></text>
        </staticText>
        <staticText>
            <reportElement x="100" y="0" width="100" height="20"/>
            <text><![CDATA[Second column with filter]]></text>
        </staticText>
        <staticText>
            <reportElement x="200" y="0" width="100" height="20">
                <property name="net.sf.jasperreports.export.xls.auto.filter" value="End"/>
            </reportElement>
            <text><![CDATA[Third (Last) column with filter]]></text>
        </staticText>
        <staticText>
            <reportElement x="300" y="0" width="100" height="20"/>
            <text><![CDATA[Fourth column without filter]]></text>
        </staticText>            
    </band>
</columnHeader>

The property can be set in Jaspersoft Studio with help of context menu or manually by editing jrxml file.

enter image description here

Понравилась статья? Поделить с друзьями:
  • Jasper report to excel
  • Jason mraz a word with you
  • Japanese words with english word
  • Japanese word zen means
  • Japanese word with sounds