[javaWeb]Struts 2导出excel文件
一、功能:将界面table数据,导出为excel文件保存
二、具体实现:
2.1 jsp
序号 书名 作者 价格
1 科幻世界 匿名 10
2 语文 驾教育出版社 23.5
3 落花 张三 10.5
注:button: <input type="button" value="导出excel" onclick="exportExcel()">
确定 引入调用的正确 js文件
2.2 js
[html]
<span style="font-size:14px;">function exportExcel(){
alert("导出");
var archiveaccount = document.forms['arcAccount'];
archiveaccount.submit();
}</span>
2.3 action
[java]
<span style="font-size:14px;">public String exportExcel() throws Exception {
List<List<Object>> data = getExportData(); //将表格数据转换为list,此方法省略
String fn = new String(("ArchiveAccount"+new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())).getBytes(), "ISO-8859-1")+ ".xls"; //设置导出文件名
if(createExcel(fn, data, "统计结果")){
return "success";
}
return "init";
}</span>
[java]
<span style="font-size:14px;"> /**
* 创建新的Excel 工作簿
* */
public boolean createExcel(String filename, List<List<Object>> data,String sheetName) {
HSSFWorkbook workbook = null;
HSSFSheet sheet = null;
HSSFRow[] rows = null;
HSSFCell[][] cells = null;
workbook = new HSSFWorkbook();
if (sheetName.trim().equals("")) {
sheet = workbook.createSheet("表");
} else {
sheet = workbook.createSheet(sheetName);
}
try {
int row = 0;
int col = 0;
if (data.size() > 0) {
row = data.size();
col = data.get(0).size();
}
rows = new HSSFRow[row];
cells = new HSSFCell[row][col];
for (int i = 0; i < data.size(); i++) {
rows[i] = sheet.createRow((short) i);
for (int j = 0; j < data.get(i).size(); j++) {
cells[i][j] = rows[i].createCell((short) j);
cells[i][j].setCellType(HSSFCell.CELL_TYPE_STRING);
if (data.get(i).get(j) != null
&& !data.get(i).get(j).toString().trim().equals("")) {
cells[i][j].setCellValue(data.get(i).get(j).toString()
.trim());
} else {
cells[i][j].setCellValue("");
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HttpUitls.getResponse().setHeader("Content-disposition","attachment; filename=" +filename);
workbook.write(baos);
byte[] ba = baos.toByteArray();
excelStream = new ByteArrayInputStream(ba);
return true;
} catch (Exception e) {
return false;
}
}</span>
2.4 struts.xml
[html]
<span style="font-size:14px;"> <action name="*ArchiveAccount" class="com.personalize.action.archiveaccount.ArchiveAccountAction" method="{1}">
<result name="init">jspNew/archiveaccount/ArchiveAccount.jsp</result>
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param> <!-- 注意这里的ContentType -->
<param name="contentDisposition">attachment;filename="${fileName}"</param> <!-- 导出文件名 -->
<param name="inputName">excelStream</param> <!-- 这里需要和Action里的变量名一致 -->
&nb
补充:Web开发 , 其他 ,