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<String> 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<data.size();i++){
	    	JSONObject jsonData = data.getJSONObject(i);
	    	HSSFRow row = sheet.createRow(i+1);
	    	for(int j=0;j<keyList.size();j++){
	    		String key = keyList.get(j);
	    		row.createCell(j,HSSFCell.CELL_TYPE_STRING)
	    		   .setCellValue(jsonData.getString(key));
	    	}
	    }
	    ByteArrayOutputStream bos = new ByteArrayOutputStream();
	    try {
			workBook.write(bos);
		} catch (IOException e) {
			throw new RuntimeException("export excel error");
		}
		return bos;
	}
}


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);
	}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值