L’objectif de cet article est de présente une façon très simple de générer des rapports Excel en Java, via l’utilisation du framework MVC Spring.
1) Une petite explication :
Le framework spring (http://www.springframework.org) met à notre disposition tous les outils utiles à la création de documents PDF. Spring etant un framework MVC propre, la creation d’un Fichier Excel passe par la réalisation d’un Controller et d’une Vue qui etend AbstractExcelView.
Voici un exemple de code…
2) Un controller… :
Alors voici un exemple de controller Spring très simple, qui va juste deposer dans le model une valeur de test, utile pour valider le fonctionnement de notre vue.
Chemin : com.tellaw.test.controllers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.tellaw.test.controllers; import java.util.*; import javax.servlet.http.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.ModelAndView; @SuppressWarnings("unchecked") public class ExcelController extends AbstractController { protected final Log logger = LogFactory.getLog(getClass()); public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); model.put ("testValue", "Ma String de test de ma vue Excel !!!"); return new ModelAndView("excel-view", "model", model); } } |
3) Une vue excel :
Voici la vue, qui va permettre de mettre en forme le document Excel. La vue se base sur l’API POI de Apache, permettant l’exploitation de documents microsofts (excels, words, powerpoints…) en Java.
Chemin : com.tellaw.test.controllers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
package com.tellaw.test.view; import java.util.*; import javax.servlet.http.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.hssf.util.Region; import org.springframework.web.servlet.view.document.AbstractExcelView; @SuppressWarnings("unchecked") public class ExcelExportView extends AbstractExcelView { protected final Log logger = LogFactory.getLog(getClass()); private static String SHEET_NAME = "feuille"; protected void buildExcelDocument( Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response ) { model = (Map<String, Object>)model.get("model"); // Get Active Datas workbook = addSkeleton( workbook ); // Define Style HSSFCellStyle style = workbook.createCellStyle(); HSSFFont boldFont = workbook.createFont(); boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); style.setFillForegroundColor( HSSFColor.LIGHT_TURQUOISE.index ); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setFont(boldFont); // Define headers cell = getCell( sheet, 1, 1 ); cell.setCellStyle( style ); // Number setText ( cell , model.get("testValue") ); } private HSSFWorkbook addSkeleton ( HSSFWorkbook workbook ) { HSSFSheet sheet; HSSFCell cell; sheet = workbook.createSheet( ExcelExportView.SHHET_NAME ); // Define Style HSSFCellStyle style = workbook.createCellStyle(); HSSFFont boldFont = workbook.createFont(); boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); style.setFont(boldFont); // Define headers cell = getCell( sheet, 3, 1 ); cell.setCellStyle(style); setText ( cell , "valeur de test du model ?" ); autoSizeCols( sheet ); return workbook; } } |
4) Configurer sur contexte Spring :
Il suffit ensuite de faire le wiring de ces objets dans le contexte de Spring…
Chemin : WEB-INF/springapp-servlet.xml (propre à mon test)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!-- Abstract Controller --> <bean id="abstractController" abstract="true" class="com.tellaw.test.controllers.AbstractController"/> <!-- EXCEL Export controller --> <bean id="excelView" class="com.tellaw.test.controllers.ExcelExportView"> </bean> <bean id="excelController" class="com.tellaw.test.controllers.ExcelController" parent="abstractController"/> <!-- Url Mapping Definition With Authentication --> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/report.xls">excelController</prop> </props> </property> </bean> <!-- View Resolver --> <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views"/> </bean> </beans> |
5) Mapper la vue via un properties :
J’aime bien séparer le mapping des vues dans un fichier Properties externe, voici le détail du mien :
Chemin : ressources/views.properties (propre à mon test et à ma compilation maven)
1 |
excel-view.(class)=com.tellaw.test.controllers.ExcelExportView |
5) Annèxes, et la suite ????
- Framework Spring : http://www.springframework.org
- Apache POI (Apache POI – Java API To Access Microsoft Format Files): http://poi.apache.org/