Excel表格内容导出到页面

 

 

public void addExcelBooks() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
String filepath = request.getParameter("filepath");
String fileType = filepath.substring(filepath.lastIndexOf("."));
InputStream is = null;
Workbook wb = null;
try {
String filedir = ServletActionContext.getServletContext().getRealPath(filepath);
File file = new File(filedir);
is = new FileInputStream(file);
if (fileType.equals(".xls")) {
wb = new HSSFWorkbook(is);
} else if (fileType.equals(".xlsx")) {
wb = new XSSFWorkbook(is);
} else {
throw new Exception("读取的不是Excel文件");
}
JSONArray jsonarr = new JSONArray();
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {//excel的sheet
Sheet hf = wb.getSheetAt(numSheet);
if (hf == null) {
continue;
}
JSONObject jsonChildObj = new JSONObject();
for (int rowNum = 1; rowNum <= hf.getLastRowNum(); rowNum++) {
Row hr = hf.getRow(rowNum);
if (hr == null) {
break;
}
Cell hxh = hr.getCell(0);
Cell hca = hr.getCell(1);
Cell hcb = hr.getCell(2);
if (hca == null || hca.toString().equals("") || hcb == null || hcb.toString().equals("") || hxh == null || hxh.toString().equals("")) {
break;
}
if (hxh.getCellType() != Cell.CELL_TYPE_NUMERIC) {判断类型对否excel表的第一列为书序为int类型对应的就是CELL_TYPE_NUMERIC
jsonChildObj.put("fail", "FAIL");
jsonarr.add(jsonChildObj);
// throw new Exception("文件内容格式错误");
} else {
int xnumber = (int) hr.getCell(0).getNumericCellValue();
String name = hr.getCell(1).getStringCellValue();
int revision = (int) hr.getCell(2).getNumericCellValue();

//这里转换为json类型前台通过ajax获得
jsonChildObj.put("xnumber", xnumber);
jsonChildObj.put("name", name);
jsonChildObj.put("revision", revision);
jsonarr.add(jsonChildObj);
}
}
}
jsonPrint(jsonarr);

} catch (FileNotFoundException e) {
throw e;
} finally {
if (wb != null) {
wb = null;
}
if (is != null) {
is.close();
}
}
}

 

posted on 2017-07-28 15:17  牛奶糖13号  阅读(212)  评论(0编辑  收藏  举报

导航