JSP页面将数据从mysql导出到excel的Java代码
2015-12-19 · 做真实的自己 用良心做教育
jsp要从mysql导出数据到顷誉excel分两步操作:
后台查询mysql符合条件的数据,放在session中。
页面展示数据,并且卖乎态控制导出,添加一个按钮中源,调用导出方法执行。
举例说明:
Java代码
sql = "select * from tablename";
rs = stmt.executeQuery(sql);
//新建Excel文件
String filePath=request.getRealPath("aaa.xls");
File myFilePath=new File(filePath);
if(!myFilePath.exists())
myFilePath.createNewFile();
FileWriter resultFile=new FileWriter(myFilePath);
PrintWriter myFile=new PrintWriter(resultFile);
resultFile.close();
//用JXL向新建的文件中添加内容
OutputStream outf = new FileOutputStream(filePath);
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(outf);
jxl.write.WritableSheet ws = wwb.createSheet("sheettest", 0);
int i=0;
int j=0;
for (int k = 0; k < rs.getMetaData().getColumnCount(); k++) {
ws.addCell(new Label(k,0,rs.getMetaData().getColumnName(k+1)));
}
while(rs.next()){
out.println(rs.getMetaData().getColumnCount());
for (int k = 0; k < rs.getMetaData().getColumnCount(); k++) {
ws.addCell(new Label(k,j+i+1,rs.getString(k+1)));
}
i++;
}
wwb.write();
wwb.close();
}catch(Exception e){e.printStackTrace();}
finally{
rs.close();
conn.close();
}
response.sendRedirect("aaa.xls");
//基旅设置类型,下载
response.setContentType("application/x-download");
//设携中置保存的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
//写文件
fs = response.getOutputStream();
while ((byteread = inStream.read(buffer)) >0) {
fs.write(buffer, 0, byteread);
}
给出的都是关键辩锋山代码,看一下应该就会懂了
fs.flush();