<%@ page contentType="text/html; charset=gbk" %>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<a href="excel.action">下载文件</a>
</html>
struts.xml文件
文件内容:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="excel" class="ExcelDownloadAction">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;filename="AllUsers.xls"</param>
<param name="inputName">excelFile</param>
</result>
</action>
</package>
</struts>
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class ExcelDownloadAction extends ActionSupport {
public InputStream getExcelFile() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet1");
{
// 创建表头
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("id");
cell = row.createCell((short) 1);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue("姓");
cell = row.createCell((short) 2);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue("名");
cell = row.createCell((short) 3);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue("年龄");
// 创建数据
// 第一行
row = sheet.createRow(1);
cell = row.createCell((short) 0);
cell.setCellValue("1");
cell = row.createCell((short) 1);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue("张");
cell = row.createCell((short) 2);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue("四");
cell = row.createCell((short) 3);
cell.setCellValue("23");
// 第二行
row = sheet.createRow(2);
cell = row.createCell((short) 0);
cell.setCellValue("2");
cell = row.createCell((short) 1);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue("李");
cell = row.createCell((short) 2);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue("六");
cell = row.createCell((short) 3);
cell.setCellValue("30");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
workbook.write(baos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] ba = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(ba);
return bais;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return super.execute();
}
}
本文出自:http://kin111.blog.51cto.com/738881/167727