jfinal+poi导出excel

要: 近两天一直再整这个文件下载,本来一个都整不出来,得知Jfinal有个renderFile()就解决了,又碰到dwz前台报Http status: 200 OK ajaxOptions: parsererror thrownError: SyntaxError: Unexpected token,然后,改成jsp下载excel后奇迹般的Jfinal的renderFile()也通了,太高兴了,双喜呀!

废话不说了,开始了!

 方案一:JFinal的renderFile("路径")功能

  先说说我的逻辑:

    前台页面点击请求发送到后台Controller,然后Controller层主要根据所需条件进行表格的组装,组装好上传到服务器后,然后跳转到前台直接显示下载框,下载即可。

前台jsp部分:

<li><a class="icon" href="<%=basePath%>feedback/expFeedBack" ><span>导出信息</span></a></li>

Controller部分:

public void expFeedBack(){
      String time="";
      int count = 0;
      String mypath="";
      try {
       List<FeedBack> list = FeedBack.dao.find("select f.id,f.content,f.datatime,f.tele from feedback f");
       count = list.size();
       time = DateUtil.formatDate();
       String path = new File("").getAbsolutePath().replaceAll("\\\\", "/"); //获得Tomcat的默认路径
       mypath = path.substring(0,path.lastIndexOf("/"))+"/webapps/3d/excel/"+time+"-"+count+"条.xlsx"; //截取字符串
       FileOutputStream os = new FileOutputStream(mypath);
       Workbook workBook = new SXSSFWorkbook(100); // 只在内存中保留100行记录
       Sheet  sheet = workBook.createSheet();
       try {
        int i=0;
        Row row1 = sheet.createRow(i++);
        Cell  cell = row1.createCell(0);
        cell.setCellValue("id"); 
        cell = row1.createCell(1);
        cell.setCellValue("反馈内容");
        cell = row1.createCell(2);
        cell.setCellValue("反馈时间"); 
        cell = row1.createCell(3);
        cell.setCellValue("联系方式");
        cell = row1.createCell(4);
        for (int j = 0; j < list.size(); j++) {
         row1 = sheet.createRow(i++);
         cell = row1.createCell(0);
         cell.setCellValue(list.get(j).getInt("id"));
         cell = row1.createCell(1);
         cell.setCellValue(list.get(j).getStr("content"));
         cell = row1.createCell(2);
         cell.setCellValue(list.get(j).getStr("datatime"));
         cell = row1.createCell(3);
         cell.setCellValue(list.get(j).getStr("tele"));
         cell = row1.createCell(4);
        }
        workBook.write(os);
       }catch(Exception e){
        e.printStackTrace();
       }
      } catch (FileNotFoundException e1) {
       e1.printStackTrace();
      }
      //判断路径是否存在
     if(new File(mypath).isFile()){
        renderFile(new File(mypath));
      }else{
        renderNull();
      }
  }


然后就愉快的可以下载了

方案二:jsp页面做成的下载【给人以假象的感觉】

jsp导出excel其实就是后台查询完数据放入list集合中,然后跳转到jsp,然后jsp按照规定的格式显示出来,并且前台弹出框,所以就有了jsp下载excel

前台jsp部分:

<li><a class="icon" href="<%=basePath%>feedback/expFeedBack" ><span>导出信息</span></a></li>

然后就是后台部分:

 
setAttr("feedBackList", FeedBack.dao.find("select * from feedback"));
 renderJsp("/admin/download.jsp");

这里的download.jsp是我做的一个下载弹出框要弹出格式的页面,内容如下

<%@ page contentType="application/vnd.ms-excel; charset=gbk" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" pageEncoding="GBK" import="com.dxcm.common.util.*"%>
<%
 String time = DateUtil.formatDate();
    String filename = new String((time).getBytes("GBK"),"ISO-8859-1"); 
   
    response.setHeader("Content-disposition","attachment; filename="+filename+".xls");
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body >
    <table border="1">
        <tr>
         <td>ID</td>
         <td>反馈内容</td>
         <td>反馈时间</td>
         <td>联系方式</td>
        </tr>
        <c:forEach items="${feedBackList}" var ="f">
         <tr>
          <td>${f.id}</td>
          <td>${f.content}</td>
          <td>${f.datatime}</td>
          <td>${f.tele}</td>
         </tr>
        </c:forEach>
 </table>
</body>
</html>


这里我用的是EL表达式遍历的后台传出来的集合。

以上代码属本人归纳总结,如有问题,还请多多指教。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面我将为您提供一个简单的demo示例,使用jfinal+vue+el来实现一个用户管理系统。 1. 准备工作 首先,需要安装Java环境和Maven工具。然后,创建一个Maven项目,并添加以下依赖: ```xml <dependency> <groupId>com.jfinal</groupId> <artifactId>jfinal</artifactId> <version>4.9.06</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency> ``` 2. 创建数据库表 在MySQL中创建一个名为user的表,包含以下字段: - id - username - password - nickname - email 3. 创建后端代码 创建一个UserController类,用于处理用户相关的请求。 ```java public class UserController extends Controller { public void index() { render("index.html"); } public void list() { int pageNumber = getParaToInt("page"); int pageSize = getParaToInt("limit"); Page<User> userList = User.dao.paginate(pageNumber, pageSize, "select *", "from user"); renderJson(JSON.toJSONString(userList)); } public void save() { User user = getModel(User.class, ""); if (user.save()) { renderJson(JSON.toJSONString(Result.success())); } else { renderJson(JSON.toJSONString(Result.failure("保存失败"))); } } public void update() { User user = getModel(User.class, ""); if (user.update()) { renderJson(JSON.toJSONString(Result.success())); } else { renderJson(JSON.toJSONString(Result.failure("更新失败"))); } } public void delete() { Integer id = getParaToInt("id"); if (User.dao.deleteById(id)) { renderJson(JSON.toJSONString(Result.success())); } else { renderJson(JSON.toJSONString(Result.failure("删除失败"))); } } } ``` 创建一个User类,用于操作数据库。 ```java public class User extends Model<User> { public static final User dao = new User().dao(); public Integer getId() { return getInt("id"); } public void setId(Integer id) { set("id", id); } public String getUsername() { return getStr("username"); } public void setUsername(String username) { set("username", username); } public String getPassword() { return getStr("password"); } public void setPassword(String password) { set("password", password); } public String getNickname() { return getStr("nickname"); } public void setNickname(String nickname) { set("nickname", nickname); } public String getEmail() { return getStr("email"); } public void setEmail(String email) { set("email", email); } } ``` 4. 创建前端代码 创建一个index.html文件,用于展示用户列表和添加用户。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>User Management System</title> <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.1/theme-chalk/index.css"> </head> <body> <div id="app"> <el-container> <el-header> <h1 style="color: white">用户管理系统</h1> </el-header> <el-main> <el-table :data="userList" border style="width: 100%"> <el-table-column label="ID" prop="id"></el-table-column> <el-table-column label="用户名" prop="username"></el-table-column> <el-table-column label="昵称" prop="nickname"></el-table-column> <el-table-column label="邮箱" prop="email"></el-table-column> <el-table-column label="操作"> <template slot-scope="scope"> <el-button type="primary" @click="editUser(scope.row)">编辑</el-button> <el-button type="danger" @click="deleteUser(scope.row)">删除</el-button> </template> </el-table-column> </el-table> <el-pagination :total="total" :page-size="pageSize" :current-page.sync="currentPage" @current-change="getPage"></el-pagination> <el-form :model="user" ref="userForm" label-width="80px" style="margin-top: 20px;"> <el-form-item label="用户名" prop="username"> <el-input v-model="user.username" placeholder="请输入用户名"></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input v-model="user.password" placeholder="请输入密码"></el-input> </el-form-item> <el-form-item label="昵称" prop="nickname"> <el-input v-model="user.nickname" placeholder="请输入昵称"></el-input> </el-form-item> <el-form-item label="邮箱" prop="email"> <el-input v-model="user.email" placeholder="请输入邮箱"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="saveUser">保存</el-button> <el-button @click="resetForm">重置</el-button> </el-form-item> </el-form> </el-main> </el-container> </div> <script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script> <script src="https://cdn.staticfile.org/element-ui/2.15.1/index.js"></script> <script src="https://cdn.staticfile.org/axios/0.21.1/axios.min.js"></script> <script type="text/javascript"> new Vue({ el: '#app', data: { userList: [], total: 0, pageSize: 10, currentPage: 1, user: { username: '', password: '', nickname: '', email: '' } }, created: function () { this.getPage(1); }, methods: { getPage: function (page) { let _this = this; axios.get('/user/list', { params: { page: page, limit: _this.pageSize } }).then(function (response) { _this.userList = response.data.list; _this.total = response.data.total; }).catch(function (error) { console.log(error); }); }, editUser: function (row) { this.user = row; }, deleteUser: function (row) { let _this = this; let id = row.id; axios.post('/user/delete', { id: id }).then(function (response) { _this.getPage(_this.currentPage); }).catch(function (error) { console.log(error); }); }, saveUser: function () { let _this = this; this.$refs.userForm.validate(function (valid) { if (valid) { axios.post('/user/save', _this.user).then(function (response) { _this.getPage(_this.currentPage); _this.resetForm('userForm'); }).catch(function (error) { console.log(error); }); } else { return false; } }); }, resetForm: function (formName) { this.$refs[formName].resetFields(); this.user = { username: '', password: '', nickname: '', email: '' }; } } }); </script> </body> </html> ``` 5. 配置路由 在JFinalConfig类中配置路由。 ```java public class DemoConfig extends JFinalConfig { @Override public void configConstant(Constants me) { me.setDevMode(true); } @Override public void configRoute(Routes me) { me.add("/user", UserController.class); } @Override public void configPlugin(Plugins me) { DruidPlugin dp = new DruidPlugin("jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8", "root", "123456"); me.add(dp); ActiveRecordPlugin arp = new ActiveRecordPlugin(dp); me.add(arp); arp.addMapping("user", User.class); } @Override public void configInterceptor(Interceptors me) { } @Override public void configHandler(Handlers me) { } } ``` 6. 运行项目 运行项目,访问http://localhost:8080/user/index即可看到用户管理系统页面。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值