public class ExcelUtil {
/**
* 方法说明:解析第一张表数据
*
* @param workbook
* @return
*/
public static Map<String, Object> parseSheet(Workbook workbook) {
HashMap<String,Object> map = new HashMap<String, Object>();
List<TestVO> list = new ArrayList<TestVO>();
//读取第一张表
Sheet sheet = workbook.getSheetAt(0);
if (null == sheet) {
map.put("flag", "F");
map.put("msg", "sheet为null");
return map;
}
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
for (int i = firstRowNum+1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);//获取当前行
//读取三列
TestVO testVO = new TestVO();
Cell cell0 = row.getCell(0);
Cell cell1 = row.getCell(1);
Cell cell2 = row.getCell(2);
testVO.setTerminalNum(getCellValue(cell0));
testVO.setMeterNum(getCellValue(cell1));
testVO.setTableModel(getCellValue(cell2));
list.add(testVO);
}
map.put("resData", list);
map.put("flag", "T");
map.put("msg", "success");
return map;
}
/**
* 方法说明:解析excel文件
*
* @param file
* @return
*/
public static Map<String, Object> parseExcel(File file) {
HashMap<String,Object> map = null;
String filePath = file.getAbsolutePath();
String filename = file.getName();
FileInputStream is = null;
try {
is = new FileInputStream(file);
Workbook workbook = null;
//判断excel文件名后缀
if (filename.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(is);
} else if (filename.endsWith(".xls")) {
//OfficeXmlFileException 为2003和2007excel版本兼容异常,出现异常io流会关闭
try {
workbook = new HSSFWorkbook(is);
} catch (OfficeXmlFileException e) {
is = new FileInputStream(file);
workbook = new XSSFWorkbook(is);
}
}
map = (HashMap<String, Object>) parseSheet(workbook);
} catch (FileNotFoundException e) {
map.put("msg", "file not found");
e.printStackTrace();
} catch (IOException e) {
map.put("msg", "created workbook is fail");
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
map.put("msg", "InputStream close exception");
e.printStackTrace();
}
}
return map;
}
/**
* 方法说明:解析单元格格式获得值
*
* @param cell
* @return
*/
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
//读取日期
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cellValue = sdf.format(cell.getDateCellValue());
} else {
//避免excel数据科学计算法
DecimalFormat df = new DecimalFormat("0");
cellValue = df.format(cell.getNumericCellValue()).trim();
}
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue()).trim();
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue()).trim();
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula()).trim();
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
/**
* 方法说明:文件下载
*
* @param request
* @param response
*/
public static void downloadFile(HttpServletRequest request,
HttpServletResponse response) throws Exception {
File obj = null;
// 用于显示的文件名
String fileName = "Batch_Import.xls";
// 获取文件路径,服务器web下路径
String rootPath = request.getSession().getServletContext()
.getRealPath("/");
String path = rootPath + "/template/" + fileName;
obj = new File(path);
if (!obj.exists()) {
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("模板不存在,请重新上传");
return;
}
InputStream blobStream = new FileInputStream(obj);
ServletOutputStream outStream = response.getOutputStream();
response.setContentType("application/OCTET-STREAM;charset=utf-8");
fileName = fileName.trim();
response.addHeader("Content-disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"), "ISO-8859-1") + "");
byte[] buffer = new byte[1024 * 1024];
int nbytes = 0;
while ((nbytes = blobStream.read(buffer)) != -1) {
outStream.write(buffer, 0, nbytes);
}
outStream.flush();
outStream.close();
blobStream.close();
}
}