displaytag的Excel导出实践
本文转自 http://lingceng.iteye.com/blog/1820081/
Displaytag官网有1.0, 1.1, 1.2等,注意找到对应的版本。源码和API可以在Maven库中找到。
常规的使用不是问题,这里说说关于Excel导出的问题,中文乱码,使用POI等。我使用的是Displaytag1.1。
基本导出功能
这种情况只需引入displaytag-1.1.jar。
设置column属性media="html"将不会导出,media="excel"不会页面显示,默认既显示又导出。
setProperty也可以写在displaytag.properties中应用于所有表格。
<display:table name="test" export="true" id="currentRowObject">
<display:column property="id" title="ID" />
<display:column property="email" />
<display:column property="status" />
<display:column media="html" property="date" />
<display:setProperty name="export.excel" value="true" />
<display:setProperty name="export.excel.filename" value="export.xls" />
</display:table>
这时候导出的excel打开的时候office会报警,但是能够打开,因为这不是正真的excel,只是csv改了后缀的纯文本格式。可能出现中文乱码,通过重载ExcelView来解决。
Class SimpleChineseExcelView extends ExcelView {
public String getMimeType(){
//原代码是return "application/vnd.ms-excel";
return "application/vnd.ms-excel;charset=gbk";
}
}
修改displaytag.properties中对应条目:
export.excel.class=yourpackage.SimpleChineseExcelView
这样就勉强能用了,只要能够忍受每次都需要另存为excel来避免报警,不用中文文件名,不在bodycontent中使用中文。这样的实现只能是差强人意。中文问题解决
使用POI
需要引入额外的displaytag-export-excel-1.1.jar,使用Maven解决依赖。
修改displaytag.properties中对应条目:
export.excel.class=org.displaytag.export.excel.ExcelHssfView
配置export filter:
<!--Configure the Filter in your web.xml:-->
<filter>
<filter-name>ResponseOverrideFilter</filter-name>
<filter-class>org.displaytag.filter.ResponseOverrideFilter</filter-class>
</filter>
<!--And add mappings for urls the filter will intercept, for example:-->
<filter-mapping>
<filter-name>ResponseOverrideFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>ResponseOverrideFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
filter-mapping加在struts之前,acegi之后(如果有),放struts之后会出问题。
很好地解决各种中文问题,也是真正的excel。
实践Hack:
项目中已经有了poi3.6,而displaytag-export-excel-1.1依赖的是poi3.0,版本太高,需要重新写一个ExcelHssfView。其实很简单,找到ExcelHssfView的源码,删除其中的所有的setEncoding方法,setEncoding方法在poi3.6中没有。修改后的代码如下,当然记得修改export.excel.class:
package com.lingceng; import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator; import javax.servlet.jsp.JspException; import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
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.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.displaytag.Messages;
import org.displaytag.exception.BaseNestableJspTagException;
import org.displaytag.exception.SeverityEnum;
import org.displaytag.export.BinaryExportView;
import org.displaytag.model.Column;
import org.displaytag.model.ColumnIterator;
import org.displaytag.model.HeaderCell;
import org.displaytag.model.Row;
import org.displaytag.model.RowIterator;
import org.displaytag.model.TableModel; /**
* Excel exporter using POI HSSF.
* @author Fabrizio Giustina
* @author rapruitt
* @version $Revision: 1.2 $ ($Author: fgiust $)
*/
public class MyExcelHssfView implements BinaryExportView
{ /**
* TableModel to render.
*/
private TableModel model; /**
* export full list?
*/
private boolean exportFull; /**
* include header in export?
*/
private boolean header; /**
* decorate export?
*/
private boolean decorated; /**
* Generated sheet.
*/
private HSSFSheet sheet; /**
* @see org.displaytag.export.ExportView#setParameters(TableModel, boolean, boolean, boolean)
*/
public void setParameters(TableModel tableModel, boolean exportFullList, boolean includeHeader,
boolean decorateValues)
{
this.model = tableModel;
this.exportFull = exportFullList;
this.header = includeHeader;
this.decorated = decorateValues;
} /**
* @return "application/vnd.ms-excel"
* @see org.displaytag.export.BaseExportView#getMimeType()
*/
public String getMimeType()
{
return "application/vnd.ms-excel"; //$NON-NLS-1$
} /**
* @see org.displaytag.export.BinaryExportView#doExport(OutputStream)
*/
public void doExport(OutputStream out) throws JspException
{
try
{
HSSFWorkbook wb = new HSSFWorkbook();
sheet = wb.createSheet("-"); int rowNum = 0;
int colNum = 0; if (this.header)
{
// Create an header row
HSSFRow xlsRow = sheet.createRow(rowNum++); HSSFCellStyle headerStyle = wb.createCellStyle();
headerStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);
headerStyle.setFillBackgroundColor(HSSFColor.BLUE_GREY.index);
HSSFFont bold = wb.createFont();
bold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
bold.setColor(HSSFColor.WHITE.index);
headerStyle.setFont(bold); Iterator iterator = this.model.getHeaderCellList().iterator(); while (iterator.hasNext())
{
HeaderCell headerCell = (HeaderCell) iterator.next(); String columnHeader = headerCell.getTitle(); if (columnHeader == null)
{
columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName());
} HSSFCell cell = xlsRow.createCell((short) colNum++);
cell.setCellValue(columnHeader);
cell.setCellStyle(headerStyle);
//cell.setEncoding(HSSFCell.ENCODING_UTF_16);
}
} // get the correct iterator (full or partial list according to the exportFull field)
RowIterator rowIterator = this.model.getRowIterator(this.exportFull);
// iterator on rows while (rowIterator.hasNext())
{
Row row = rowIterator.next();
HSSFRow xlsRow = sheet.createRow(rowNum++);
colNum = 0; // iterator on columns
ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList()); while (columnIterator.hasNext())
{
Column column = columnIterator.nextColumn(); // Get the value to be displayed for the column
Object value = column.getValue(this.decorated); HSSFCell cell = xlsRow.createCell((short) colNum++);
//cell.setEncoding(HSSFCell.ENCODING_UTF_16); if (value instanceof Number)
{
Number num = (Number) value;
cell.setCellValue(num.doubleValue());
}
else if (value instanceof Date)
{
cell.setCellValue((Date) value);
}
else if (value instanceof Calendar)
{
cell.setCellValue((Calendar) value);
}
else
{
cell.setCellValue(escapeColumnValue(value));
} }
}
wb.write(out);
}
catch (Exception e)
{
throw new ExcelGenerationException(e);
}
} // patch from Karsten Voges
/**
* Escape certain values that are not permitted in excel cells.
* @param rawValue the object value
* @return the escaped value
*/
protected String escapeColumnValue(Object rawValue)
{
if (rawValue == null)
{
return null;
}
String returnString = ObjectUtils.toString(rawValue);
// escape the String to get the tabs, returns, newline explicit as \t \r \n
returnString = StringEscapeUtils.escapeJava(StringUtils.trimToEmpty(returnString));
// remove tabs, insert four whitespaces instead
returnString = StringUtils.replace(StringUtils.trim(returnString), "\\t", " ");
// remove the return, only newline valid in excel
returnString = StringUtils.replace(StringUtils.trim(returnString), "\\r", " ");
// unescape so that \n gets back to newline
returnString = StringEscapeUtils.unescapeJava(returnString);
return returnString;
} /**
* Wraps IText-generated exceptions.
* @author Fabrizio Giustina
* @version $Revision: 1.2 $ ($Author: fgiust $)
*/
static class ExcelGenerationException extends BaseNestableJspTagException
{ /**
* D1597A17A6.
*/
private static final long serialVersionUID = 899149338534L; /**
* Instantiate a new PdfGenerationException with a fixed message and the given cause.
* @param cause Previous exception
*/
public ExcelGenerationException(Throwable cause)
{
super(ExcelHssfView.class, Messages.getString("ExcelView.errorexporting"), cause); //$NON-NLS-1$
} /**
* @see org.displaytag.exception.BaseNestableJspTagException#getSeverity()
*/
public SeverityEnum getSeverity()
{
return SeverityEnum.ERROR;
}
} }
displaytag的Excel导出实践的更多相关文章
- java 导出 excel 最佳实践,java 大文件 excel 避免OOM(内存溢出) excel 工具框架
产品需求 产品经理需要导出一个页面的所有的信息到 EXCEL 文件. 需求分析 对于 excel 导出,是一个很常见的需求. 最常见的解决方案就是使用 poi 直接同步导出一个 excel 文件. 客 ...
- appfuse:Excel导出
1.pom.xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...
- VB-机房收费系统之Excel导出
敲机房很久了,感觉对代码的感知力终于有所提高了,很是开心.今天在敲学生充值记录查询的时候发现,其中有了新的知识, 这时候就该到了分析问题的时候了.不说废话了! 首先 保证自己的笔记本或者电脑上必须有 ...
- 百万级别数据Excel导出优化
前提 这篇文章不是标题党,下文会通过一个仿真例子分析如何优化百万级别数据Excel导出. 笔者负责维护的一个数据查询和数据导出服务是一个相对远古的单点应用,在上一次云迁移之后扩展为双节点部署,但是发现 ...
- [moka同学笔记]PHPexcel之excel导出和导入
原案例来自http://www.sucaihuo.com/有修改 1.目录结构(文件不用解释,应该都可以看得懂,直接看代码)
- 偷懒小工具 - Excel导出公共类
说明 最近接了一个任务,就是做一个列表的Excel导出功能.并且有很多页面都会使用这个功能. 导出的Excel大体格式如图 很简单的列表,标题加背景色,然后不同类型,显示方式不一样.对齐方式不一样.不 ...
- 转:POI操作Excel导出
package com.rd.lh.util.excel; import java.beans.PropertyDescriptor; import java.io.FileOutputStream; ...
- TP5.0源生Excel导出
PHPExcel类在TP5里边并不能很好的兼容,使用起来很麻烦. 不像是tp3.2那样直接import()加进来就能new,因为它里边的命名空间找不到.总是说undefined class. 如果是使 ...
- java反射学习之二万能EXCEL导出
一.EXCEL导出的实现过程 假设有一个对象的集合,现在需要将此集合内的所有对象导出到EXCEL中,对象有N个属性:那么我们实现的方式是这样的: 循环这个集合,在循环集合中某个对象的所有属性,将这个对 ...
随机推荐
- Android WiFi开发
概述 介绍Android WiFi的扫描.连接.信息.以及WiFi热点等等的实现,并用代码实现. 详细 代码下载:http://www.demodashi.com/demo/10660.html 一. ...
- 在MyEclipse中改动jsp页面的默认打开方式
在JavaWeb项目中.当然有非常多jsp页面,可是我发现,双击打开jsp页面总是卡机.相对于打开其它java文件而言非常慢,感觉非常不舒服.MyEclipse中默认打开jsp页面是以可视化的形式展现 ...
- 在sys用户下执行的sql脚本创建了摁多个表和序列, 怎么回退?
一个个删除, 暂时不会别的方法...
- HDUOJ----(1016)Prime Ring Problem
Prime Ring Problem Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Other ...
- Google map API V3
本文主要总结Google map API V3使用中最简单也是最常见的一些操作以及相关概念,如果需要更加详细的信息,请直接阅读Google提供的关于map的文档. google map api v3文 ...
- C# 采用钩子捕获键盘和鼠标事件-验证是否处于无人操作状态
原文地址:https://www.cnblogs.com/gc2013/p/4036414.html 全局抽象类定义 using System; using System.Collections.Ge ...
- 【js】右下角浮动窗口
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- LevelDB场景分析2--Open
1.源码 1 Status DB::Open(const Options& options, const std::string& dbname, uint64_t new_ ...
- Linux内核jiffies简介
在LINUX的时钟中断中涉及至二个全局变量一个是xtime,它是timeval数据结构变量,另一个则是jiffies,首先看timeval结构struct timeval{time_t tv_sec; ...
- Spark与Pandas中DataFrame对比
Pandas Spark 工作方式 单机single machine tool,没有并行机制parallelism不支持Hadoop,处理大量数据有瓶颈 分布式并行计算框架,内建并行机制paral ...