Vertx_web导出excel文档

项目中遇到一个需要将订单详情导出为excel的功能,记录如下:

public class ExcelUtil {
	/**
	 * convert json to excel
	 * @param data
	 * @param sheetName
	 * @return
	 */
	public static ByteArrayOutputStream getExcelFile(JSONArray data,String sheetName){
		if(data==null||data.size()==0){
			return null;
		}
		HSSFWorkbook workBook = new HSSFWorkbook();
		HSSFSheet sheet = workBook.createSheet(sheetName);
		HSSFRow tableHead = sheet.createRow(0);
		HSSFCellStyle style = workBook.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		JSONObject item = data.getJSONObject(0);
		ArrayList keyList = new ArrayList<>();
		int index = 0;
	    for(String key:item.keySet()){
	    	tableHead.createCell(index,HSSFCell.CELL_TYPE_STRING).setCellValue(key);
	    	keyList.add(index, key);
	    	index++;
	    }
	    for(int i=0;i


public void exportOrder(RoutingContext context){
		JSONObject json1 = new JSONObject();
		json1.put("name", "chensongxia");
		json1.put("age", "25");
		JSONObject json2 = new JSONObject();
		json2.put("name", "zhaoru");
		json2.put("age", "25");
		JSONArray data = new JSONArray();
		data.add(json1);
		data.add(json2);
		Buffer buffer = Buffer.buffer();  
		buffer.appendBytes(ExcelUtil.getExcelFile(data, "sheet1").toByteArray());
		context.response().putHeader("content-type", "application/octet-stream;charset=UTF-8");
		context.response().putHeader("Content-Disposition", "attachment;filename=order.xls"); 
		context.response().putHeader("Pargam", "no-cache");  
		context.response().putHeader("Cache-Control", "no-cache");
		context.response().end(buffer);
	}



你可能感兴趣的:(JAVA相关)