1、工具
工欲善其事,必先利其器,我打算把数据库中的数据导出成为Excel表格,到网上搜了一下需要的工具: - POI
POI下载地址:
- Poi.jar
- 官网下载
相关代码参考:
-java导出数据库的全部表到excel
2、具体操作步骤
jar包导入问题
如上方式导入后,但是打包发布时显示找不到对应的包,真是奇怪。
于是按照如下方式:
1 、在src同级别目录下创建libs文件夹;
2、把对应的jar包直接复制进去,简单粗暴;
3、然后在gradle.build文件中添加依赖即可,然后就一切OK。
dependencies
{
compile files('libs/poi.jar')
}
private File createExcel(File file) {
if(!file.exists()){
file.mkdirs() ;
}
File filenew = new File(file.getAbsoluteFile()+"/MotionRecord.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("table");
HSSFRow row = sheet.createRow((int) 0);
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("UserId");
cell.setCellStyle(style);
cell = row.createCell((short) 1);
cell.setCellValue("time");
cell.setCellStyle(style);
cell = row.createCell((short) 2);
cell.setCellValue("state");
cell.setCellStyle(style);
List list = null;
try {
list = getMotionRecord();
} catch (Exception e1) {
e1.printStackTrace();
}
for (int i = 0; i < list.size(); i++)
{
row = sheet.createRow((int) i + 1);
MotionRecord stu = (MotionRecord) list.get(i);
row.createCell((short) 0).setCellValue((double) stu.getUserId());
row.createCell((short) 1).setCellValue(stu.getTime());
row.createCell((short) 2).setCellValue((double) stu.getState());
}
try
{
FileOutputStream fout = new FileOutputStream(filenew);
wb.write(fout);
fout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return filenew;
}
private List<MotionRecord> getMotionRecord() throws Exception
{
List list = new ArrayList();
MotionRecord user1 = new MotionRecord(1, Timestamp.valueOf(LocalDateTime.now()),1);
MotionRecord user2 = new MotionRecord(2, Timestamp.valueOf(LocalDateTime.now()),1);
MotionRecord user3 = new MotionRecord(3, Timestamp.valueOf(LocalDateTime.now()),1);
list.add(user1);
list.add(user2);
list.add(user3);
return list;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
3、步骤总结
- 第一步,创建一个webbook,对应一个Excel文件
- 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
- 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
- 第四步,创建单元格,并设置值表头 设置表头居中
- 第五步,写入实体数据 实际应用中这些数据从数据库得到
- 第六步,将文件存到指定位置