Home Java javaTutorial An example of dynamic column printing using jasperReport in Java

An example of dynamic column printing using jasperReport in Java

Sep 18, 2017 am 09:41 AM
java Print

This article mainly introduces the relevant information about the implementation code of jasperReport in Java to implement dynamic column printing. I hope that everyone can master this part of the content through this article. Friends in need can refer to

Java The implementation code of jasperReport to implement dynamic column printing

The comments in the following code are very clear. I hope it can help everyone. Please refer to it.

Sample code:


public ActionResult projectPrint() { 
  String[] printValue = null; 
  // 从页面中获得要查询的字段 
  String reqPrintValue = getRequest().getParameter("printValue"); 
  // 没有选择则默认全打印 
  if (null == reqPrintValue || StringUtils.isEmpty(reqPrintValue)) { 
   printValue = new String[] { "pnumber", "pname", "pdepart", "pdecision", "pthrow", "plastmonth", "pfund", "ploan" }; 
  } else { 
   printValue = reqPrintValue.split(","); 
  } 
  // 查询统计数据 
  List<Object[]> projectList = getEntityManager().queryPrintProjectInfo(printValue); 
 
  // 将数据转换为Map对象,换化成Map对象 
  List<Map> reportDataList = new ArrayList<Map>(); 
 
  for (int i = 0; i < projectList.size(); i++) { 
   Object[] personStr = projectList.get(i); 
   Map reportData = new HashMap(); 
   for (int j = 0; j < personStr.length; j++) { 
    reportData.put("field_" + j, String.valueOf(personStr[j])); 
   } 
   reportDataList.add(reportData); 
  } 
 
  int columCount = 0;// 数据列 
  int fieldCount = 0;// 字段列数(因为pname比较长所以想让pname比其它的列长些,故设计这个变量) 
  int pnameCount = -1;// 记录下pname的序号 
  for (int i = 0; i < printValue.length; i++) { 
   // pthrow下面有两列 
   if ("pthrow".equals(printValue[i])) { 
    columCount = columCount + 2; 
    fieldCount = fieldCount + 2; 
    // ploan下面也有两列 
   } else if ("ploan".equals(printValue[i])) { 
    columCount = columCount + 2; 
    fieldCount = fieldCount + 2; 
    // 故意让pname也占两列 
   } else if ("pname".equals(printValue[i])) { 
    pnameCount = i;// 记录下pname的序号 
    columCount = columCount + 1; 
    fieldCount = fieldCount + 2; 
   } else { 
    // 其它的列都占一个单位 
    columCount = columCount + 1; 
    fieldCount = fieldCount + 1; 
   } 
  } 
 
  InputStream is = null; 
  try { 
   // 从资源文件中读取报表 
   is = this.getClass().getResourceAsStream("/reports/project.jrxml"); 
   JasperDesign jasperDesign = (JasperDesign) JRXmlLoader.load(is); 
 
   Map styleMap = jasperDesign.getStylesMap(); 
   // column header 对应的样式 
   JRDesignStyle theaderStyle = (JRDesignStyle) styleMap.get("theader"); 
   // column detail 对应的样式 
   JRDesignStyle tbodyStyle = (JRDesignStyle) styleMap.get("tboby"); 
   // pagefoot 对应的样式 
   JRDesignStyle tfootStyle = (JRDesignStyle) styleMap.get("tfoot"); 
 
   int _START_X_ = 20;// x轴的起始位置 
   int startX = _START_X_; // x轴的起始位置 
   // 单列的宽度 
   // 535是jasepreReport报表column最大的宽度 
   int columnWidth = 535 / fieldCount; 
   // 20,24,15是报表中已设置的,一定与之相同 
   final int columnHeadBandHeight = 20; 
   final int detailHeight = 24; 
   final int pagefootHeight = 15; 
 
   // 设置报表字段 
   for (int idx = 0; idx < columCount; idx++) { 
    JRDesignField field = new JRDesignField(); 
    field.setName("field_" + idx); 
    field.setValueClass(java.lang.String.class); 
    jasperDesign.addField(field); 
   } 
 
   JRDesignBand columnHeadBand = (JRDesignBand) jasperDesign.getColumnHeader(); 
   // 绘制表头 
   for (int idx = 0; idx < printValue.length; idx++) { 
    if ("pnumber".equals(printValue[idx])) { 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     staticText.setWidth(columnWidth); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(2 * columnHeadBandHeight); 
     staticText.setText("序号"); 
     columnHeadBand.addElement(staticText); 
     startX += columnWidth; 
    } else if ("pname".equals(printValue[idx])) { 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     // 项目名称的宽度是其它的宽度的2倍 
     staticText.setWidth(columnWidth * 2); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(2 * columnHeadBandHeight); 
     staticText.setText("项目名称"); 
     columnHeadBand.addElement(staticText); 
     startX += columnWidth * 2; 
    } else if ("pdepart".equals(printValue[idx])) { 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     staticText.setWidth(columnWidth); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(2 * columnHeadBandHeight); 
     staticText.setText("部门"); 
     columnHeadBand.addElement(staticText); 
     startX += columnWidth; 
    } else if ("pdecision".equals(printValue[idx])) { 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     staticText.setWidth(columnWidth); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(2 * columnHeadBandHeight); 
     staticText.setText("已决策"); 
     columnHeadBand.addElement(staticText); 
     startX += columnWidth; 
    } else if ("pthrow".equals(printValue[idx])) { 
     // 投审会下面有两列 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     staticText.setWidth(columnWidth * 2); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("投审会"); 
     columnHeadBand.addElement(staticText); 
 
     staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     columnHeadBand.addElement(staticText); 
     staticText.setWidth(columnWidth); 
     staticText.setY(columnHeadBandHeight); 
     staticText.setX(startX); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("12月初"); 
 
     staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     columnHeadBand.addElement(staticText); 
     staticText.setWidth(columnWidth); 
     staticText.setY(columnHeadBandHeight); 
     staticText.setX(startX + columnWidth); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("12月中"); 
     columnHeadBand.addElement(staticText); 
     startX += 2 * columnWidth; 
    } else if ("plastmonth".equals(printValue[idx])) { 
     // 投决会下面有一列 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     staticText.setWidth(columnWidth); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("投决会"); 
     columnHeadBand.addElement(staticText); 
 
     staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     columnHeadBand.addElement(staticText); 
     staticText.setWidth(columnWidth); 
     staticText.setY(columnHeadBandHeight); 
     staticText.setX(startX); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("12月下"); 
     columnHeadBand.addElement(staticText); 
     startX += columnWidth; 
    } else if ("pfund".equals(printValue[idx])) { 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     staticText.setWidth(columnWidth); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(2 * columnHeadBandHeight); 
     staticText.setText("基金投资额"); 
     columnHeadBand.addElement(staticText); 
     startX += columnWidth; 
    } else if ("ploan".equals(printValue[idx])) { 
     // 投贷协同额下面有两列 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     staticText.setWidth(columnWidth * 2); 
     staticText.setY(0); 
     staticText.setX(startX); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("投贷协同额"); 
     columnHeadBand.addElement(staticText); 
 
     staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     columnHeadBand.addElement(staticText); 
     staticText.setWidth(columnWidth); 
     staticText.setY(columnHeadBandHeight); 
     staticText.setX(startX); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("金额"); 
 
     staticText = new JRDesignStaticText(); 
     staticText.setStyle(theaderStyle); 
     columnHeadBand.addElement(staticText); 
     staticText.setWidth(columnWidth); 
     staticText.setY(columnHeadBandHeight); 
     staticText.setX(startX + columnWidth); 
     staticText.setHeight(columnHeadBandHeight); 
     staticText.setText("入库情况"); 
     columnHeadBand.addElement(staticText); 
     startX += 2 * columnWidth; 
    } 
   } 
 
   // 绘制Detail部门 
   startX = _START_X_; 
   JRDesignBand columnDetailBand = (JRDesignBand) jasperDesign.getDetail(); 
   for (int idx = 0; idx < columCount; idx++) { 
    JRDesignTextField textField = new JRDesignTextField(); 
    textField.setStretchWithOverflow(true); 
    textField.setX(startX); 
    textField.setY(0); 
    if (pnameCount == idx) { 
     textField.setWidth(2 * columnWidth); 
     startX += 2 * columnWidth; 
    } else { 
     textField.setWidth(columnWidth); 
     startX += columnWidth; 
    } 
    textField.setHeight(detailHeight); 
    textField.setPositionType(JRElement.POSITION_TYPE_FLOAT); 
    textField.setStyle(tbodyStyle); 
    textField.setBlankWhenNull(true); 
    JRDesignExpression expression = new JRDesignExpression(); 
    expression.setValueClass(java.lang.String.class); 
    expression.setText("$F{field_" + idx + "}"); 
    textField.setExpression(expression); 
    columnDetailBand.addElement(textField); 
   } 
 
   JRDesignBand pageFootBand = (JRDesignBand) jasperDesign.getPageFooter(); 
   // 合计数据,本应统计的 
   List<Object[]> pageCountList = new ArrayList<Object[]>(); 
   Object[] obj = new String[] { "合计", "15299", "", "", "67121", "92420", "155877", }; 
   pageCountList.add(obj); 
   obj = new String[] { "", "", "", "XXX小计", "", "24473", "16470", }; 
   pageCountList.add(obj); 
   obj = new String[] { "", "", "", "WWW小计", "", "7289", "1674", }; 
   pageCountList.add(obj); 
   obj = new String[] { "", "", "", "ZZZ小计", "", "32700", "13000", }; 
   pageCountList.add(obj); 
   obj = new String[] { "", "", "", "YYY小计", "", "12733", "120733", }; 
   pageCountList.add(obj); 
   obj = new String[] { "", "", "", "AAA小计", "", "2225", "120733", }; 
   pageCountList.add(obj); 
   obj = new String[] { "", "", "", "BBB小计", "", "3000", "0", }; 
   pageCountList.add(obj); 
   int footWidth = 535 / 7; 
   for (int p = 0; p < pageCountList.size(); p++) { 
    for (int k = 0; k < 7; k++) { 
     Object[] ob = pageCountList.get(p); 
     JRDesignStaticText staticText = new JRDesignStaticText(); 
     staticText.setStyle(tfootStyle); 
     staticText.setWidth(footWidth); 
     staticText.setY(pagefootHeight * p); 
     staticText.setX(k * footWidth + _START_X_); 
     staticText.setHeight(pagefootHeight); 
     staticText.setText(String.valueOf(ob[k])); 
     pageFootBand.addElement(staticText); 
    } 
   } 
 
   // 编译报表 
   JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); 
   String type = this.getRequest().getParameter("type");//pdf格式 
   JasperUtils.prepareReport(jasperReport, type); 
   // 报表数据源 
   JRDataSource dataSource = new JRBeanCollectionDataSource(reportDataList); 
   JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource); 
   HttpServletResponse response = this.getResponse(); 
   JasperUtils.export(jasperPrint, response, getRequest(), type); 
  } catch (Exception e) { 
   e.printStackTrace(); 
  } 
 
  return null; 
 }
Copy after login


public static void export(JasperPrint jasperPrint, HttpServletResponse response, HttpServletRequest request, 
   String type) throws IOException { 
  if (EXCEL_TYPE.equals(type)) { 
   exportExcel(jasperPrint, response, request); 
  } else if (PDF_TYPE.equals(type)) { 
   exportPDF(jasperPrint, response, request); 
  } else if (HTML_TYPE.equals(type)) { 
   exportHTML(jasperPrint, response, request); 
  } else { 
   exportPrint(jasperPrint, response, request); 
  } 
 
 }
Copy after login


public static void exportExcel(JasperPrint jasperPrint, HttpServletResponse response, HttpServletRequest request) 
   throws IOException { 
  response.setContentType("application/vnd.ms-excel"); 
  String filename = DownloadHelper.encodeFilename("未命名.xls", request); 
  response.setHeader("Content-disposition", "attachment;filename=" + filename); 
  ServletOutputStream ouputStream = response.getOutputStream(); 
  JRXlsExporter exporter = new JRXlsExporter(); 
  exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); 
  exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream); 
  exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); 
  exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); 
  exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); 
  try { 
   exporter.exportReport(); 
  } catch (JRException e) { 
   e.printStackTrace(); 
  } 
  ouputStream.flush(); 
  ouputStream.close(); 
 } 
 
 public static void exportPDF(JasperPrint jasperPrint, HttpServletResponse response, HttpServletRequest request) 
   throws IOException { 
  response.setContentType("application/pdf"); 
  String filename = DownloadHelper.encodeFilename("未命名.pdf", request); 
  response.setHeader("Content-disposition", "attachment;filename=" + filename); 
  ServletOutputStream ouputStream = response.getOutputStream(); 
  try { 
   JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream); 
  } catch (JRException e) { 
   e.printStackTrace(); 
  } 
  ouputStream.flush(); 
  ouputStream.close(); 
 }
Copy after login

The above is the detailed content of An example of dynamic column printing using jasperReport in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles