您的位置:首页 > 编程语言 > Java开发

用Java实现下载功能,并保存到excel表格中

2017-11-29 11:30 337 查看

一,通过POI接口,将从数据库中查出的信息以excel的形式存储

1.首先写一个Utils类
public class DownPOIUtils {

/**
*
* @param response:响应对象,类型是HttpServletResponse
* @param map:要封装的信息的map容器,其中key为Student,value为String类型的,在这里代表分数
* @throws Exception:代表异常对象
*/
public static void downPoi(HttpServletResponse response,
Map<Student, String> map) throws Exception {
String fname = "detial" + getTimeStamp();// Excel文件名
OutputStream os = response.getOutputStream();// 取得输出流
response.reset();// 清空输出流
response.setHeader("Content-disposition", "attachment; filename="
+ fname + ".xls"); // 设定输出文件头,该方法有两个参数,分别表示应答头的名字和值。
response.setContentType("application/msexcel");
try {
new DownPOIUtils().new POIS().createFixationSheet(os, map);

} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 该方法用来产生一个时间字符串(即:时间戳)
* @return
*/
public static String getTimeStamp() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:MM:ss");
Date date = new Date();
return dateFormat.format(date);
}
2.编写POI代码
class POIS {

public void createFixationSheet(OutputStream os,
Map<Student, String> student) throws Exception {
// 创建工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 在工作薄上建一张工作表
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
sheet.createFreezePane(0, 1);
cteateCell(wb, row, (short) 0, "学号");
cteateCell(wb, row, (short) 1, "姓名");
cteateCell(wb, row, (short) 2, "性别");
cteateCell(wb, row, (short) 3, "班级");
cteateCell(wb, row, (short) 4, "分数");
int i = 0;
Set<Student> keySet = student.keySet();
Iterator<Student> iterator = keySet.iterator();
while (iterator.hasNext()) {
HSSFRow rowi = sheet.createRow((short) (++i));
Student student2 = iterator.next();
for (int j = 0; j < 4; j++) {
cteateCell(wb, rowi, (short) 0, student2.getId());
cteateCell(wb, rowi, (short) 1, student2.getName());
cteateCell(wb, rowi, (short) 2, student2.getSex());
cteateCell(wb, rowi, (short) 3, student2.getGrade());
cteateCell(wb, rowi, (short) 4, student.get(student2));
}
}
wb.write(os);
os.flush();
os.close();
System.out.println("文件生成");

}

@SuppressWarnings("deprecation")
private void cteateCell(HSSFWorkbook wb, HSSFRow row, short col,
String val) {
HSSFCell cell = row.createCell(col);
cell.setCellValue(val);
HSSFCellStyle cellstyle = wb.createCellStyle();
cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
cell.setCellStyle(cellstyle);
}
}


3.效果如下图:



4.打开可以看到数据已经写入:



5.总结:
在本次代码中,可以看到调用下载的方法的参数中,数据是被放到Map容器中的,其中的key是一个对象,value是一个分数类型是String。当然封装数据的参数也可以List类型的,只不过要看我们实际需求,如果从数据库中查出的信息不是一张表,那么就不能用一个实体对象来封装,所以可以使用map。在本次代码中,student作为map 的key,尽量在Student类中重写一下hashcode方法和equals方法,保证map的键值得唯一性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息