您的位置:首页 > 编程语言 > Java开发

Vertx_web导出excel文档

2016-08-05 16:57 405 查看
项目中遇到一个需要将订单详情导出为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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vertx java