Java Excelインスタンスのエクスポート
28851 ワード
@ResponseBody
@RequestMapping(value = "export", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public void export(@RequestParam(value = "settleId", required = true) Integer settleId,
HttpServletResponse response) {
String fileName = "export_" + BaseUtil.nowDateToStr() + ".xls";
File f = new File(fileName);
JSONArray paymentDetails;
JSONObject settlement = new JSONObject();
String[] fields = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"};
BaseUtil.FieldTypes[] types = {BaseUtil.FieldTypes.STRINGTOSTRING, BaseUtil.FieldTypes.STRINGTOSTRING,
BaseUtil.FieldTypes.UNCHANGE,BaseUtil.FieldTypes.UNCHANGE,BaseUtil.FieldTypes.UNCHANGE,
BaseUtil.FieldTypes.STRINGTOSTRING,BaseUtil.FieldTypes.UNCHANGE,BaseUtil.FieldTypes.UNCHANGE,
BaseUtil.FieldTypes.UNCHANGE,BaseUtil.FieldTypes.UNCHANGE,BaseUtil.FieldTypes.UNCHANGE,};
try {
paymentDetails = settlementService.exportSettlement(settlement, fields, types, settleId);
// Excel
if (!f.exists()) {
f.createNewFile();
}
String sourceFileName = this.getClass().getResource("/template").getPath() + "exportSettlement.xls";
File sf = new File(sourceFileName);
ExcelUtil.copyTo(sf, f);
Workbook wb = ExcelUtil.openForWrite(fileName);
Sheet sheet = wb.getSheetAt(0);
if (wb != null) {
//
//Row 1
String v;
Row row = sheet.getRow(1);
Cell cell = row.getCell(2);//organizationName
v = settlement.getString("enrollBatch");
cell.setCellValue(v);
cell = row.getCell(7);//remittanceName
v = settlement.getString("settlementName");
cell.setCellValue(v);
cell = row.getCell(12);
v = settlement.getString("operator");
cell.setCellValue(v);
// //Row 2
row = sheet.getRow(2);
cell = row.getCell(2);//payBeginDate
v = settlement.getString("studyCenterName");
cell.setCellValue(v);
cell = row.getCell(7);
v = settlement.getString("settleDate");
cell.setCellValue(v);
cell = row.getCell(12);
v = settlement.getString("auditor");
cell.setCellValue(v);
//
// //Row 3
row = sheet.getRow(3);
cell = row.getCell(2);
v = settlement.getString("paySchoolYear");
cell.setCellValue(v);
cell = row.getCell(7);
v = settlement.getString("remitBeginDate");
cell.setCellValue(v);
//Row 4
row = sheet.getRow(4);
cell = row.getCell(2);
v = settlement.getString("projectType");
cell.setCellValue(v);
cell = row.getCell(7);
v = settlement.getString("remitEndDate");
cell.setCellValue(v);
//Row 5
row = sheet.getRow(5);
cell = row.getCell(2);
v = settlement.getString("serialNumber");
cell.setCellValue(v);
//
if (paymentDetails != null) {
for (int i = 0; i < paymentDetails.size(); i++) {
JSONObject jo = paymentDetails.getJSONObject(i);
row = sheet.createRow(i + 7);
ExcelUtil.writeRow(wb, row, jo, fields);
}
}
}
ExcelUtil.saveAsNewFile(fileName, wb);
String contentType = "application/vnd.ms-excel;charset=utf-8";
DownloadUtil.download(response, f, contentType, new String(f.getName().getBytes("UTF-8")));
} catch (Exception e) {
logger.error(" ", e);
} finally {
try {
if (f != null) {
f.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//sql
StringBuffer sql = new StringBuffer( "select s.student_name, s.identity_card, p.pay_school_year, p.pay_tuition, sum(p.pay_money) as pay_money, e.student_source, sum(p.channel_deduct) as channel_deduct, cpr.current_percentage, ((p.pay_tuition - sum(case when p.discount_type = ' ' then p.discount_money else 0 end)) * current_percentage / 100) as channel_amount, 0 as channel_payback, ((sum(p.pay_money) - sum(case when p.discount_type = ' ' then p.discount_money else 0 end)) * current_percentage / 100 - sum(p.channel_deduct)) as channel_need_payback, sum(case when p.discount_type = ' ' then p.discount_money else 0 end) as discount_money"); sql.append(" from student s left join student_enroll e on s.student_id = e.student_id left join payment_detail p on s.student_id = p.student_id left join channel_protocol cp on s.channel_id = cp.channel_id left join channel_protocol_reward cpr on cp.protocol_id = cpr.channel_protocol_id"); sql.append(" where p.settlement_id = " + settleId); sql.append(" group by s.student_name, s.identity_card, p.pay_school_year, p.pay_tuition, e.student_source, cpr.current_percentage"); List resultList = settlementDao.findBySql(sql.toString()); return BaseUtil.convertSqlResultToJson(fields,types,resultList);
// sql, List
@Override public List findBySql(String sql) { return getEntityManager().createNativeQuery(sql).getResultList(); }
// converSqlFieldToJson
public static JSONObject convertSqlFieldToJson(String[] keys,FieldTypes[] types,Object[] values) throws ParseException { JSONObject o = new JSONObject(); for (int i = 0;i < keys.length;i++) { String key = keys[i]; FieldTypes type; if(types == null){ type = FieldTypes.UNCHANGE; } else { type = types[i]; } SimpleDateFormat sdf = null; Object value = values[i]; Date d = null; switch (type) { case INTEGERTOSTRING: if (value == null){ o.put(key,""); } else { Integer iv = (Integer) value; o.put(key, iv.toString()); } break; case FLOATTOSTRING: if (value == null){ o.put(key,""); } else { Float fv = (Float) value; o.put(key, fv.toString()); } break; case DATETOSTIRNGTIME: if (value == null){ o.put(key,""); } else { sdf = new SimpleDateFormat("HH:mm:ss"); java.sql.Date qtv = (java.sql.Date) value; d = new Date(qtv.getTime()); o.put(key, sdf.format(d)); } break; case DATETOSTRINGDATE: if (value == null){ o.put(key,""); } else { sdf = new SimpleDateFormat("yyyy-MM-dd"); java.sql.Date qdv = (java.sql.Date) value; d = new Date(qdv.getTime()); o.put(key, sdf.format(d)); } break; case DATETOSTRINGDATETIME: if (value == null){ o.put(key,""); } else { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.sql.Date qdtv = (java.sql.Date) value; d = new Date(qdtv.getTime()); o.put(key, sdf.format(d)); } break; case STRINGTOTIMESTAMP: case STRINGTODATE: if (value == null){ o.put(key,null); } else { sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String sdv = (String) value; d = sdf.parse(sdv); o.put(key, d); } break; case STRINGTOFLOAT: if (value == null){ o.put(key,null); } else { String sfv = (String) value; o.put(key, new Float(sfv)); } break; case STRINGTOINTEGER: if (value == null){ o.put(key,null); } else { String siv = (String) value; o.put(key, new Integer(siv)); } break; case DATETODATE: if (value == null){ o.put(key,null); } else { java.sql.Date qd = (java.sql.Date) value; d = new Date(qd.getTime()); o.put(key, d); } break; case TIMESTAMPTODATE: if (value == null){ o.put(key,null); } else { java.sql.Timestamp qt = (Timestamp) value; d = new Date(qt.getTime()); o.put(key, d); } break; case STRINGTOSTRING: if (value == null){ o.put(key,""); } else { o.put(key, value); } break; case UNCHANGE: o.put(key, value); break; default: o.put(key, value); break; } } return o; }
//Excel
public static Workbook openForWrite(String fileName) throws IOException { File file = new File(fileName); Workbook wb; InputStream is; try { is = new FileInputStream(file); } catch (FileNotFoundException e) { return null; } String ext = BaseUtil.getExtendName(fileName); if (".xls".equals(ext)) { wb = new HSSFWorkbook(is); } else if (".xlsx".equals(ext)) { wb = new XSSFWorkbook(is); } else { return null; } return wb; }
// Row
public static void writeRow(Workbook wb,Row row,JSONObject value,String[] fields){ DataFormat format = wb.createDataFormat(); //---> // 1 CellStyle style = wb.createCellStyle(); // style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// style.setWrapText(true); // , true style.setBorderBottom((short) 1); // , style.setBorderLeft((short) 1); // style.setBorderRight((short) 1); // style.setBorderTop((short) 1); // style.setDataFormat(format.getFormat("¥#,##0")); //---> style.setDataFormat(format.getFormat("@")); Font font = wb.createFont(); font.setFontHeightInPoints((short) 10); //---> font.setFontName("Courier New"); //---》 , : font.setItalic(true); //---> style.setFont(font); //---> style1 for(int i = 0;i < fields.length;i++){ Cell cell = row.createCell(i); cell.setCellStyle(style); String key = fields[i]; String v = value.getString(key); cell.setCellValue(v); } }
// new File
public static void saveAsNewFile(String fileName,Workbook wb) throws IOException { OutputStream os = new FileOutputStream(fileName); wb.write(os); os.close(); }
// download
public static void download(HttpServletResponse response,File f,String contentType,String fileName){ download(response, f, contentType, fileName, 8192); }