关于使用struts2控制excel文件下载在这里只是介绍其中的一种方法
一、关于jsp页面
expGridToExcel : function(condition) {
/**
* 导出数据到excel
*/
var cm = this.contentPanel.getColumnModel();
var colHeaderStr = "";
var colDataIndexStr = "";
for (var i = 1; i < cm.getColumnCount(); i++) {
if (!cm.isHidden(i)) {
if (cm.getDataIndex(i)) {
colHeaderStr = colHeaderStr + cm.getColumnHeader(i) + ",";
colDataIndexStr = colDataIndexStr + cm.getDataIndex(i)
+ ",";
}
}
}
condition['colHeaderStr'] = colHeaderStr;
condition['colDataIndexStr'] = colDataIndexStr;
/*if (!Ext.fly('test')) {
var frm = document.createElement('form');
frm.id = 'test';
frm.name = id;
frm.style.display = 'none';
document.body.appendChild(frm);
}
Ext.Ajax.request({
url : '../map/busReportAction!expOldAdv',
form : Ext.fly('test'),
method : 'POST',
isUpload : true,
params : condition
});*/
window.open('../map/busReportAction!expOldAdv?'+encodeURI(encodeURI($.param(condition))));
},
说明:colDataIndexStr :指的是对应属性名字,比如: tent,begintime,endtime,telephone
colHeaderStr :指的是表头名字,比如: 广告 ID, 广告商 , 广告内容等。
二、关于action层
public String expOldAdv() throws UnsupportedEncodingException {
try {
List<BusOldadvertisementinfo> list = null;
BusOldadvertisementinfo oldAd = new BusOldadvertisementinfo();
oldAd.setCompanyname(getDecodeData(companyName));
String beginTimeDecode = this.getDecodeData(beginTime);
String endTimeDecode = this.getDecodeData(endTime);
if (beginTimeDecode != null && beginTimeDecode.length() == 10) {
oldAd.setBegintime(DateUtil.parseYYYYMMDDDate(beginTimeDecode));
}
if (endTimeDecode != null && endTimeDecode.length() == 10) {
oldAd.setEndtime(DateUtil.parseYYYYMMDDDate(endTimeDecode));
}
// 给出查询的条件,以及页,根据条件得到要导出的数据组成的集合
list = busOldadvertisementinfoService.export(oldAd, start, limit);
String[] colHeader = URLDecoder.decode(
URLDecoder.decode(colHeaderStr, "UTF-8"), "UTF-8").split(
",");
String[] colDataIndex = URLDecoder.decode(
URLDecoder.decode(colDataIndexStr, "UTF-8"), "UTF-8")
.split(",");
// 读取模板Excel
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(0, Constance.OLDADVSHEETNAME);
// 设置字体颜色
HSSFFont font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 设置报表中单元格的样式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setFont(font);
int colCount = colHeader.length;
CellRangeAddress cellas = new CellRangeAddress(0, 0, 0,
colCount - 1);
sheet.addMergedRegion(cellas);
HSSFRow headerRow = sheet.createRow(0);
HSSFCell headerCell = headerRow.createCell(0);
headerCell.setCellStyle(style);
headerCell.setCellValue(Constance.OLDADVCELLVALUE);
int size = 0;
if (list != null) {
size = list.size();
}
for (int rownum = 1; rownum < size + 2; rownum++) {
HSSFRow r = sheet.createRow(rownum);
for (int cellnum = 0; cellnum < colHeader.length; cellnum++) {
if (rownum == 1) {
HSSFCell cell = r.createCell(cellnum);
cell.setCellValue(new HSSFRichTextString(
colHeader[cellnum]));
cell.setCellStyle(style);
} else {
//为每一行的创建单元格
HSSFCell cell = r.createCell(cellnum);
//为每个单元格赋值
cell.setCellValue(new HSSFRichTextString(this.getDataDynamic
(list.get(rownum - 2),colDataIndex[cellnum])));
//为每个单元格设置样式
cell.setCellStyle(style);
}
}
}
//确定要导出的文件的名字
fileName = new SimpleDateFormat("yyyy-MM-dd").format(new Date())
+ Constance.OLDADVCELLVALUE + ".xls";
//根据路径名和文件名创建一个FILE实例
File file = new File(ServletActionContext.getServletContext()
.getRealPath(inputPath), fileName);
//将excel模板连同数据,写到指定的file中
workbook.write(new FileOutputStream(file));
} catch (Exception e) {
log.error("GetBusDataAction queryAdv() failed", e);
} finally {
}
return SUCCESS;
}
/**
* 根据属性名称动态取出对应的值(反射读取某个对象中的某个get方兴得到对应属性的值)
*
* @param obj 集合中的某一个对象
* @param property 对象中的某个属性
* @return
*/
public String getDataDynamic(Object obj, String property) {
Class c = obj.getClass();
try {
//根据属性名称取出field
Field field = c.getDeclaredField(property);
Method method;
if (field.getType().equals(Boolean.TYPE)) {
String methodName = "is"
+ property.substring(0, 1).toUpperCase()
+ property.substring(1);
method = c.getDeclaredMethod(methodName);
} else {
String methodName = "get"
+ property.substring(0, 1).toUpperCase()
+ property.substring(1);
method = c.getDeclaredMethod(methodName);
}
//反射读取obj类中的method方法
Object o = method.invoke(obj);
if (o != null) {
if (o instanceof Date) {
return DateUtils.format((Date) o, Constance.DATEFORMATE);
} else {
if (property.equals("isaudit")) {
if ((Long) o == 1) {
return "通过审计";
} else if ((Long) o == 0) {
return "未通过审核";
} else {
return "未做处理";
}
}
return o.toString();
}
}
} catch (SecurityException e) {
log.debug(e.getMessage());
return "";
} catch (NoSuchFieldException e) {
log.debug(e.getMessage());
return "";
} catch (NoSuchMethodException e) {
log.debug(e.getMessage());
return "";
} catch (IllegalArgumentException e) {
log.debug(e.getMessage());
return "";
} catch (IllegalAccessException e) {
log.debug(e.getMessage());
return "";
} catch (InvocationTargetException e) {
log.debug(e.getMessage());
return "";
}
return "";
}
public InputStream getInputStream
() throws Exception {
String url = inputPath + "/" + fileName;
int size = url.length() - 1;
for (int i = 0; i < size; i++) {
url = url.replace("\\", "/");
}
System.out.println("url="+url);
//返回读取指定的文件流
return ServletActionContext.getServletContext()
.getResourceAsStream(url);
}
三、关于配置文件说明
<action name="busReportAction" class="busReportAction">
<param name="inputPath">/reportManage/reportFile/qiantai</param>
<result name="success" type="stream
">
<param name="contentType">application/vnd.ms-excel;charset=ISO8859-1</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">inline;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>
说明:
contentType:指定被下载文件的类型
inputName:指定被下载文件的入口输入流(它的参数的值就是方法去掉get前缀,首字母小定的字符串)
contentDisposition:指定下载的文件名
bufferSize:指定下载文件时的缓冲大小
总结:总之下载文件就是先通过一定的方法,将要导出的文件流写到服务器上也就是某个位置,然后通过struts2的
配置文件去读这个文件,就是这样一个简单的过程,至于中间如何将正确的数据写到文件中,方法有很多,我这里只是
介绍了其中的一种,通过反射的机制读取数据。
将此方法和大家分享一下,如果有更好的方法还请留言,大家共同分享~~~