스프링에서 엑셀 다운로드 기능을 만들어보자. 이때 템플릿파일과 데이터를 이용하여 최종 산출물을 만들어 보자. 이때 JXLS 를 이용할 것이다. 

 pom.xml 


<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.5-beta5</version>
</dependency>

<!-- JXLS -->
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>1.0</version>
</dependency>




 servlet-context.xml 

<!-- XML View Resolver for Excel : WEB-INF/views.xml -->
<beans:bean name="xmlViewResolver"
class="org.springframework.web.servlet.view.XmlViewResolver" p:order="1">
</beans:bean>




 views.xml 

<beans>
<!-- Excel 출력 설정 -->
<bean id="excelViewByJXLS" class="net.javapark.UserExcelView">
  <property name="contentType" value="application/vnd.ms-excel; charset=UTF-8"></property>
</bean>
</beans>




 UserExcelView 


public class UserExcelView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {

XLSTransformer transformer = new XLSTransformer();
String templateFileName = "templateFileName";
String destFileName = "destFileName";
Workbook resultWorkbook = transformer.transformXLS(new FileInputStream(templateFileName), model);

StringBuffer contentDisposition = new StringBuffer();
contentDisposition.append("attachment;fileName=\"");
contentDisposition.append(destFileName);
contentDisposition.append("\";");

response.setHeader("Content-Disposition", contentDisposition.toString());
response.setContentType("application/x-msexcel");
resultWorkbook.write(response.getOutputStream());
}
}





 Excel Template 


<jx:forEach items="${list}" var="user" varStatus="status">
${status.index+1} | ${user.name} | ${user.addr}
</jx:forEach>




 참고 



 

posted by 소연파파™