在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java导出excel时创建多个sheet

2016-7-29 15:47| 发布者: zhangjf| 查看: 694| 评论: 0

摘要: import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.List;import jxl.Workbook;import jxl.write.Label;import jxl.write.WritableSheet;import jxl.write.WritableWorkb ...
<无详细内容>
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import jxl.Workbook;
  6. import jxl.write.Label;
  7. import jxl.write.WritableSheet;
  8. import jxl.write.WritableWorkbook;
  9. import jxl.write.WriteException;
  10. /**
  11. * Title:
  12. * Description: TestDemo
  13. * @author lu
  14. * @date 2016年7月19日 下午3:17:28
  15. */
  16. public class TestDome {
  17. public static void outputExcelData() throws IOException, WriteException {
  18. /*1、设置写入excel表格的值
  19. * 这里可扩展为在数据中调取的相关的数据*/
  20. List<User> result = new ArrayList<User>();
  21. User user = new User();
  22. user.setId("1");
  23. user.setName("zhangshang");
  24. result.add(user);
  25. User user2 = new User();
  26. user2.setId("1");
  27. user2.setName("shanghai");
  28. result.add(user2);
  29. User user3 = new User();
  30. user3.setId("1");
  31. user3.setName("beijing");
  32. result.add(user3);
  33. /*2、设置文件的名字和导出的位置
  34. * 这里可扩展为服务器地址或者是硬盘地址*/
  35. String fileName = "D://sfData.xls";
  36. /*3、Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象*/
  37. WritableWorkbook wwb = Workbook.createWorkbook(new File(fileName));
  38. File dbfFile = new File(fileName);
  39. if (!dbfFile.exists() || dbfFile.isDirectory()) {
  40. dbfFile.createNewFile();
  41. }
  42. int totle = result.size();//获取List集合的size
  43. int mus = 2;//每个工作表格最多存储2条数据(注:excel表格一个工作表可以存储65536条)
  44. int avg = totle / mus;
  45. for (int i = 0; i < avg + 1; i++) {
  46. WritableSheet ws = wwb.createSheet("列表" + (i + 1), i); //创建一个可写入的工作表
  47. //添加表头
  48. ws.addCell(new Label(0, 0, "序号"));
  49. ws.addCell(new Label(1, 0, "姓名"));
  50. int num = i * mus;
  51. int index = 0;
  52. for (int m = num; m < result.size(); m++) {
  53. if (index == mus) {//判断index == mus的时候跳出当前for循环
  54. break;
  55. }
  56. User use = (User) result.get(m);
  57. //将生成的单元格添加到工作表中
  58. //(这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行)
  59. ws.addCell(new Label(0, index + 1, use.getId()));
  60. ws.addCell(new Label(1, index + 1, use.getName()));
  61. index++;
  62. }
  63. }
  64. wwb.write();//从内存中写入文件中
  65. wwb.close();//关闭资源,释放内存
  66. }
  67. //测试
  68. public static void main(String[] args) {
  69. try {
  70. outputExcelData();
  71. System.out.println("导出完成!");
  72. } catch (WriteException e) {
  73. e.printStackTrace();
  74. } catch (IOException e) {
  75. e.printStackTrace();
  76. }
  77. }
  78. }
复制代码
上一篇:HashMap下一篇:买钱买百鸡

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 13:30

Copyright 2015-2025 djqfx

返回顶部