@POST
@Path("export")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ResultBean exportRoadSegmentGpsInfo(List<String> ids, @Context HttpServletRequest request){
ResultBean result = new ResultBean(ErrorCode.OK);
if (ids.isEmpty()){
LOGGER.error("parameter orror,id is null!");
result.setCode(ErrorCode.PARA_IS_ERROR);
return result;
}
List<Integer> idlist = new ArrayList<Integer>();
for (String id : ids){
idlist.add(Integer.valueOf(id));
}
List<RoadSegmentGpsBean> roadSegmentGpsBeans = null;
try {
roadSegmentGpsBeans = roadSegmentGpsDao.queryRoadSegmentsByIds(idlist);
} catch (Exception e) {
LOGGER.error("query data from db error: " + e.getMessage());
e.printStackTrace();
result.setCode(ErrorCode.DB_FAIL);
return result;
}
if (StringUtils.isEmpty(WEB_ROOT_PATH)){
WEB_ROOT_PATH = request.getServletContext().getRealPath("/");
}
//根据查询结果生成excel
long currentTime = System.currentTimeMillis();
String exclePath = this.generateExcel(roadSegmentGpsBeans,currentTime);
if (StringUtils.isNotEmpty(exclePath)){
String excelUrl = "http://" + request.getRemoteHost() + "/" + WEB_ROOT_NAME + "/" + TEMP_EXCEL_PATH + "/" + currentTime + "/" + EXCEL_NAME;
result.addEntry("src", excelUrl);
}
return result;
}
/**
* 生成excel文件
* @param recordBeans recordBeans
* @return excel 文件的相对路径
*/
private String generateExcel(List<RoadSegmentGpsBean> recordBeans,long currentTime) {
Workbook workbook = new HSSFWorkbook();
HSSFCellStyle style = ((HSSFWorkbook) workbook).createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
Sheet sheet = workbook.createSheet("考勤数据");
//创建表头
Row rowHeader = sheet.createRow(0);
int length = EXCEL_HEADER.length;
for (int i = 0;i < length;i++){
rowHeader.createCell(i).setCellValue(EXCEL_HEADER[i]);
}
//写入考勤数据
int i = 1;
for (RoadSegmentGpsBean bean : recordBeans){
Row row = sheet.createRow(i++);
row.createCell(0).setCellValue(bean.getRoadId());
row.createCell(1).setCellValue(bean.getRoadCode());
row.createCell(2).setCellValue(bean.getRoadName());
row.createCell(3).setCellValue(bean.getGps1());
row.createCell(4).setCellValue(bean.getGps2());
row.createCell(5).setCellValue(bean.getGps3());
row.createCell(6).setCellValue(bean.getGps4());
}
//调整列宽
for (int j = 0;j < length;j++){
sheet.autoSizeColumn(j);
}
String tempExcelDir = WEB_ROOT_PATH + File.separator + TEMP_EXCEL_PATH + File.separator + currentTime;
File excelDir = new File(tempExcelDir);
if (!excelDir.exists()){
excelDir.mkdirs();
}
File excel = new File(tempExcelDir + File.separator + EXCEL_NAME);
OutputStream os = null;
try {
if (!excel.exists()){
excel.createNewFile();
}
os = new FileOutputStream(excel);
workbook.write(os);
os.flush();
} catch (IOException e){
LOGGER.error("数据写入excel异常,文件不存在!");
return null;
}
finally {
if (null != os){
try {
os.close();
} catch (IOException e) {
LOGGER.error("关闭流失败");
}
}
}
return excel.getAbsolutePath();
}