首页 文章 精选 留言 我的

精选列表

搜索[java],共10000篇文章
优秀的个人博客,低调大师

Java 导入数据到Excel并提供文件下载接口

最近的项目中遇到了一个将数据库的信息导入到一个 Excel 文件的需求,而且还要提供下载该 Excel 文件的接口 ,搞定之后,进行了一下总结,希望给大家带来帮助 源码: https://github.com/HowieYuan/Excel-Download 依赖 <!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl --> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6.12</version> </dependency> 我们需要用到 jxl 包的类,而 jxl.jar 正是操作 excel 表格的工具类库,除了 jxl 以外,poi 包也是一个 操作 excel 的类库。 而对比两个包,jxl 更适用与数据量大的情况,而 poi 在数据量不高(大约5000以内)时,效率较高,但占用内存大,更容易内存溢出。 测试数据 private int id; private String name; private int age; private String gender; public List<Person> getPersonList() { List<Person> list = new ArrayList<>(); list.add(new Person(1, "Howie", 20, "female")); list.add(new Person(2, "Wade", 25, "male")); list.add(new Person(3, "Duncan", 30, "male")); list.add(new Person(4, "Kobe", 35, "male")); list.add(new Person(5, "James", 40, "male")); return list; } 1. 将数据全部导入到一张表格 //创建文件本地文件 //直接将文件创建在项目目录中 String filePath = "人员数据.xls"; File dbfFile = new File(filePath); //使用 Workbook 类的工厂方法创建一个可写入的工作薄(Workbook)对象 WritableWorkbook wwb = Workbook.createWorkbook(dbfFile); //如果文件不存在,则创建一个新的文件 if (!dbfFile.exists() || dbfFile.isDirectory()) { dbfFile.createNewFile(); } //获得人员信息 list (PersonFactroy 类已经被依赖注入) List<Person> list = personFactroy.getPersonList(); //创建一个可写入的工作表 WritableSheet ws = wwb.createSheet("列表 1", 0); //添加excel表头 ws.addCell(new Label(0, 0, "序号")); ws.addCell(new Label(1, 0, "姓名")); ws.addCell(new Label(2, 0, "年龄")); ws.addCell(new Label(3, 0, "性别")); int index = 0; for (Person person : list) { //将生成的单元格添加到工作表中 //(这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行) ws.addCell(new Label(0, index + 1, String.valueOf(person.getId()))); ws.addCell(new Label(1, index + 1, person.getName())); ws.addCell(new Label(2, index + 1, String.valueOf(person.getAge()))); ws.addCell(new Label(3, index + 1, person.getGender())); index++; } 导入数据后的 Excel 表 2. 将数据导入到多个表格 //前面的代码一致 //每个工作表格最多存储2条数据(注:excel表格一个工作表可以存储65536条) int mus = 2; //数据的总大小 int totle = list.size(); //总表格数 int avg = totle / mus + 1; for (int i = 0; i < avg; i++) { //创建一个可写入的工作表 WritableSheet ws = wwb.createSheet("列表" + (i + 1), i); //添加excel表头 ws.addCell(new Label(0, 0, "序号")); ws.addCell(new Label(1, 0, "姓名")); ws.addCell(new Label(2, 0, "年龄")); ws.addCell(new Label(3, 0, "性别")); int num = i * mus; int index = 0; for (int m = num; m < list.size(); m++) { //判断index == mus的时候跳出当前for循环 if (index == mus) { break; } Person person = list.get(m); //将生成的单元格添加到工作表中 //(这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行) ws.addCell(new Label(0, index + 1, String.valueOf(person.getId()))); ws.addCell(new Label(1, index + 1, person.getName())); ws.addCell(new Label(2, index + 1, String.valueOf(person.getAge()))); ws.addCell(new Label(3, index + 1, person.getGender())); index++; } } 这里是根据每个表的数据量来分,大家也可以根据其中一个属性等等来分成各个表格 提供文件下载接口 该方法利用文件流来写入文件,方法类型为 void,不需要 return,除此之外,接口参数中需要添加上 HttpServletResponse @RequestMapping(value = "/getExcel", method = RequestMethod.GET) public void createBoxListExcel(HttpServletResponse response) throws Exception { String filePath = "人员数据.xls"; /** * 这部分是刚刚导入 Excel 文件的代码,省略 */ String fileName = new String("人员数据.xls".getBytes(), "ISO-8859-1"); //设置文件名 response.addHeader("Content-Disposition", "filename=" + fileName); OutputStream outputStream = response.getOutputStream(); FileInputStream fileInputStream = new FileInputStream(filePath); byte[] b = new byte[1024]; int j; while ((j = fileInputStream.read(b)) > 0) { outputStream.write(b, 0, j); } fileInputStream.close(); outputStream.flush(); outputStream.close(); } 然后,我们直接在地址栏输入localhost:8080/getExcel既可立刻下载你的文件 注意: String fileName = new String("人员信息.xlsx".getBytes(), "ISO-8859-1"); 我使用了 ISO-8859-1 编码,原因是 ISO-8859-1编码是单字节编码,向下兼容 ASCII,而 Header 中只支持 ASCII,传输的文件名必须是 ASCII

优秀的个人博客,低调大师

Java用Gson按照键值key排序json所有节点

<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> private static Comparator<String> getComparator() { Comparator<String> c = new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareTo(o2); } }; return c; } public static void sort(JsonElement e) { if (e.isJsonNull()) { return; } if (e.isJsonPrimitive()) { return; } if (e.isJsonArray()) { JsonArray a = e.getAsJsonArray(); for (Iterator<JsonElement> it = a.iterator(); it.hasNext();) { sort(it.next()); } return; } if (e.isJsonObject()) { Map<String, JsonElement> tm = new TreeMap<String, JsonElement>(getComparator()); for (Entry<String, JsonElement> en : e.getAsJsonObject().entrySet()) { tm.put(en.getKey(), en.getValue()); } for (Entry<String, JsonElement> en : tm.entrySet()) { e.getAsJsonObject().remove(en.getKey()); e.getAsJsonObject().add(en.getKey(), en.getValue()); sort(en.getValue()); } return; } } public static void main(String[] args) { try { String json = FileUtils.readFileToString(new File("C://test//test.txt"), "UTF-8"); Gson g = new GsonBuilder().setPrettyPrinting().create(); JsonParser p = new JsonParser(); JsonElement e = p.parse(json); sort(e); System.out.println(g.toJson(e)); } catch(Exception e) { e.printStackTrace(); } } 代码样例参考了自动化测试REST API工具Wisdom RESTClient https://github.com/Wisdom-Projects/rest-client

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册