1、将数据下载存储在excel表格中,代码如下:
package zh.pujin.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import zh.pujin.entity.Registeruser;
public class ExcelExport {
public String excelExport(List<Registeruser> registerUserByCondition ,HttpServletResponse resp){
int result = 0;
String[] title = {"序号","手机号","城市"}; //根据需要设置
try {
resp.setContentType("application/binary;charset=UTF-8");
ServletOutputStream out = resp.getOutputStream();
String name = "文件" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
String fileName = new String(name.getBytes("GB2312"), "ISO_8859_1");
resp.setHeader("Content-disposition", "attachment;filename="+fileName+".xls");
try{
HSSFWorkbook hwb = new HSSFWorkbook(); // 创建webBook,对应一个excel文件
HSSFSheet sheet = hwb.createSheet("数据测试"); // 添加一个sheet
HSSFRow row = sheet.createRow(0); // 标题栏
HSSFCellStyle style = hwb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFCell cell = null;
for(int i=0; i<title.length; i++){ //标题的内容
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
if(registerUserByCondition.size() > 0){
for(int i=0; i<registerUserByCondition.size(); i++){ //获取的数据
row = sheet.createRow(i+1);
row.createCell(0).setCellValue(String.valueOf(registerUserByCondition.get(i).getId()).trim());
row.createCell(1).setCellValue(String.valueOf(registerUserByCondition.get(i).getUserphone()).trim());
row.createCell(2).setCellValue(String.valueOf(registerUserByCondition.get(i).getCity()).trim());
}
}
try{
hwb.write(out);
out.flush();
out.close();
} catch(Exception e) {
e.getMessage();
result = 1;
return null;
}
} catch(Exception e){
e.getMessage();
result = 1;
return null;
}
} catch (IOException e) {
e.getMessage();
result = 1;
return null;
}
return null;
}
}