QQ截图20190214073114.png
隔着半个月后的再次更新
今天的代码功能是:在SSM框架中,将MySql数据库中的数据,导出到Excel文件中。
/**
*前台 访问a标签时,进入这个类
*/
@RequestMapping("excelshengcheng")
public void export(HttpServletResponse response,HttpServletRequest request) throws Exception{
//获取数据
List<Student> slist = userDao.selectStudent();
try {
String fname ="detial"; //Excel文件名
OutputStream os=response.getOutputStream();//获取输出流
response.reset();//清空输出流
//设定输出文件头,该方法有两个参数,分别表示应答头的名字和值。
response.setHeader("Content-Disposition", "attachment;filename="+fname+".xls");
//定义输出类型 (可选择下载位置)
response.setContentType("application/octet-stream");
//ResultSet res=userDao.selectStudent();
ExcelBeanControl eb = new ExcelBeanControl();
eb.createFixationSheet(slist, os);//调用生成excel文件bean
//res.close();
} catch (Exception e) {
// TODO: handle exception
}
}
public class ExcelBeanControl {
private HSSFWorkbook wb=null;
public ExcelBeanControl(){
wb=new HSSFWorkbook();
}
//ResultSet结果集(ResultSet)是数据中查询结果返回的一种对象
//结果集读取数据的方法主要是getXXX() ,他的参数可以使整型表示第几列(是从1开始的),还可以是列名。返回的是对应的XXX类型的值。
//OutputStream 输出流
/**
* 第一行
* @param res
* @param os
* @throws IOException
*/
public void createFixationSheet(List<Student> slist,OutputStream os) throws IOException{
HSSFSheet sheet = wb.createSheet("new sheet");//创建sheet页
wb.setSheetName(0, "sheet页名称");//HSSFWorkbook.ENCODING_UTF_16
HSSFRow row = sheet.createRow((short)0);
sheet.createFreezePane(0, 1); //冻结第一行
createCell(wb, row, (short)0, "手机号码");
createCell(wb, row, (short)1, "名称");
createCell(wb, row, (short)2, "年龄");
createCell(wb, row, (short)3, "性别");
createCell(wb, row, (short)4, "生日");
createCell(wb, row, (short)5, "兴趣");
int ii=6;
try {
//res.getMetaData().getColumnCount();获取列的数量
int i=0; //i代表这行 第几列
int jh=-1;
for (int k = 0; k < slist.size(); k++) {//一共需要输出几行数据
i++;
jh++;
List<String> stu=new ArrayList<String>();//作用:转换数据类型
HSSFRow row2 = sheet.createRow((short)i);
System.out.println("map长度"+slist.size()+i);
for (;jh < ii;) {
stu.add(slist.get(jh).getStunum());
stu.add(slist.get(jh).getStuname());
stu.add(slist.get(jh).getStuage());
stu.add(slist.get(jh).getStusex());
stu.add(slist.get(jh).getStubirthday());
stu.add(slist.get(jh).getStuhobby());
break;
}
/*for (Student student : slist) {
stu.add(student.getStunum());
stu.add(student.getStuname());
stu.add(student.getStuage());
stu.add(student.getStusex());
stu.add(student.getStubirthday());
stu.add(student.getStuhobby());
} */
for(int j=0;j<ii;j++){
String ss=stu.get(j);
System.out.println(ss+j);//res.getString(j+1);
//向单元格中添加 文件 开始行 列 数据
createCell(wb, row2, (short)j, ss);
}
}
} catch (Exception e) {
e.printStackTrace();
}
wb.write(os);
os.flush();
os.close();
} /**
* 创建单元格
*/
private void createCell(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);
}
}
为什么不用信息for循环,如图
list集合取值问题.png












网友评论