struts2中将jsp table中的数据导出到excel表格中

来源:互联网 发布:淘宝卖家怎么改优惠价 编辑:程序博客网 时间:2024/04/30 23:53

struts2中将jsp table中的数据导出到excel表格中

近日,在做一个练习,将jsp的table中显示的数据导出到excel表格中(数据来自数据库),项目使用SSH框架,jsp页面有一个连接,连接到后台一个action,该action负责把数据写入excel文件。

相关代码如下:


//jsp连接<a href="exportDataToExcel">导出数据</a>//struts2 action配置 <action name="exportDataToExcel" class="com.petstore.action.ExportDataToExcel"            method="exportData">            <result name="data">/</result> </action>//action代码public class ExportDataToExcel extends ActionSupport {    List<Log> logList = null;    public String exportData() {        Map<String, Object> session = ActionContext.getContext().getSession();        logList = (List<Log>) session.get("logList");        HttpServletResponse response = ServletActionContext.getResponse();        // 创建工作表        WritableWorkbook book = null;        // response.reset();        // 创建工作流        OutputStream os = null;        try {            // 设置弹出保存对话框            response.setContentType("application/x-msdownload");                       SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");            //文件名,以当前秒为文件名            String fileName = sdf.format(new Date());            response.setHeader("Content-Disposition", "attachment; filename="                    + fileName + ".xls");// 设置生成的文件名字            os = response.getOutputStream();            // 初始化工作表            book = Workbook.createWorkbook(os);        } catch (IOException e1) {            e1.printStackTrace();        }        try {                       WritableSheet sheet = book.createSheet("日志信息", 0);                        // 字段名            sheet.addCell(new jxl.write.Label(0, 0, "日志ID"));            sheet.addCell(new jxl.write.Label(1, 0, "用户姓名"));            sheet.addCell(new jxl.write.Label(2, 0, "用户IP"));            sheet.addCell(new jxl.write.Label(3, 0, "请求路径"));            sheet.addCell(new jxl.write.Label(4, 0, "是否登录"));            sheet.addCell(new jxl.write.Label(5, 0, "请求时间"));            // 添加数据            for (int i = 1; i < logList.size(); i++) {                sheet.addCell(new jxl.write.Label(0, i, logList.get(i)                        .toString()));                sheet.addCell(new jxl.write.Label(1, i, logList.get(i)                        .getUsername()));                sheet                        .addCell(new jxl.write.Label(2, i, logList.get(i)                                .getIp()));                sheet                        .addCell(new jxl.write.Label(3, i, logList.get(i)                                .getUrl()));                sheet.addCell(new jxl.write.Label(4, i, logList.get(i)                        .getIsSuccess()));                sheet.addCell(new jxl.write.Label(5, i, logList.get(i)                        .getDate()));            }            book.write();            book.close();        } catch (Exception e) {            e.printStackTrace();        }        return "data";    }} 

结果如图


原创粉丝点击