利用excel导出查询的记录表

我们通常碰到查询出来的表格需要用EXCEL导出,这是我学习到的一个方案,拿出来与大家分享。本文主要是给自己留下点资料以便以后查看,如果有朋友需要了解的,可以讨论下,也希望指正我的错误,还是那句话,我是个新手,希望大家提供给我帮助
(1)在struts.xml中配置action
<action name="generateExcel" class="generateExcelAction">
<result type="stream"> <paramname="contentType">application/vnd.ms-excel</param>
<paramname="contentDisposition">attchment;filename="AllUser.xls"</param>
<param name="inputName">downloadFile</param>
        </result>
</action>
(2)service层
public InputStream getInputStream() {
HSSFWorkbook wb = new HSSFWorkbook();

HSSFSheet sheet = wb.createSheet("sheel1");

HSSFRow row = sheet.createRow(0);

HSSFCell cell = row.createCell((short) 0);

cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("序号");

cell = row.createCell((short) 1);

cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("姓");

cell = row.createCell((short) 2);

cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("名");

cell = row.createCell((short) 3);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("年龄");

List<User> list = this.findAll();
for (int i = 0; i < list.size(); i++) {
User user = list.get(i);

row = sheet.createRow(i + 1);
cell = row.createCell((short) 0);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(i + 1);

cell = row.createCell((short) 1);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getFirstname());

cell = row.createCell((short) 2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getLastname());

cell = row.createCell((short) 3);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getAge());
}

//String fileName = CharacterUtils.getRandomString(10);
//或者采用
String fileName = RandomStringUtils.randomAlphanumeric(10);
fileName = new StringBuffer(fileName).append(".xls").toString();

final File file = new File(fileName);

try {
OutputStream os = new FileOutputStream(file);
try {
wb.write(os);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

InputStream is = null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//增加线程,15000为等待文件下载时间
new Thread(new Runnable(){
public void run(){
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
file.delete();
}
}).start();

return is;
}
(3)GenerateExcelAction
public InputStream getDownloadFile(){
return this.service.getInputStream();
}
(4)spring配置文件注入action
<bean id="generateExcelAction"   class="com.test.action.user.GenerateExcelAction" >
<property name="service" ref="userService"></property>
</bean>
(5)jsp
<s:a href="generateExcel.action">生成Excel</s:a>

猜你喜欢

转载自zpxiaoxiang.iteye.com/blog/1666847