JAVA實現excel表格匯出,(IDEA 匯入jar包操作)
阿新 • • 發佈:2019-01-08
1、工具
工欲善其事,必先利其器,我打算把資料庫中的資料匯出成為Excel表格,到網上搜了一下需要的工具: - POI
POI下載地址:
- Poi.jar
- 官網下載
2、具體操作步驟
- 先把poi的jar匯入,匯入方式如下:
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");
// 第一步,建立一個webbook,對應一個Excel檔案
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet
HSSFSheet sheet = wb.createSheet("table");
// 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short
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) {
// TODO Auto-generated catch block
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();
// SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
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;
}
3、步驟總結
- 第一步,建立一個webbook,對應一個Excel檔案
- 第二步,在webbook中新增一個sheet,對應Excel檔案中的sheet
- 第三步,在sheet中新增表頭第0行,注意老版本poi對Excel的行數列數有限制short
- 第四步,建立單元格,並設定值表頭 設定表頭居中
- 第五步,寫入實體資料 實際應用中這些資料從資料庫得到
- 第六步,將檔案存到指定位置