1.jar包
2.POIUtils工具类
package com.esstglobal.service.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; /** * 读写EXCEL文件 */ public class POIUtils { /** * @author Ted * @param coleNames * 列表头 * @param dataList * 数据集 * @param fileName * 下载时显示的文件名 * */ public static void exportToExcel(HttpServletResponse response, List<String> coleNames, List<Map<String, Object>> dataList, String fileName) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ExcelUtil.createWorkBook(coleNames, dataList).write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 设置response参数,可以打开下载页面 response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = response.getOutputStream(); bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (bos != null) bos.close(); } catch (IOException e) { } } } /** * @Description 通过模板导出 * @author 张洋 * @date 2017年4月1日 下午4:24:43 * @param response * @param filePath 模板路径 * @param dataList 数据 * @param fileName excel下载显示的名字 */ public static void exportToExcelByMouduel(HttpServletResponse response, String filePath, List<Map<String, Object>> dataList, String fileName) { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ExcelUtil.createWorkBookByMouduel(filePath, dataList).write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 设置response参数,可以打开下载页面 response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = response.getOutputStream(); bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (bos != null) bos.close(); } catch (IOException e) { } } } }
3.ExcelUtil 操作excel工具类
package com.esstglobal.service.utils; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; /** * 导出Excel文档工具类 * * @date 2014-8-6 * */ public class ExcelUtil { /** * 创建excel文档, * * @param listMap * 表头 * @param dataList * 数据 (Map<String,Object> 中key 要与导出的顺序对应 可以放key:1,23或a,b,c) * @param columnNames * excel的列名 * */ public static Workbook createWorkBook(List<String> listMap, List<Map<String, Object>> dataList) { // 数据 List<List<String>> listData = new ArrayList<List<String>>();// 将数据装成list<list<>> // 形式 for (int i = 0; i < dataList.size(); i++) { Map<String, Object> map = dataList.get(i); Set<String> set = map.keySet(); List<String> list2 = new ArrayList<String>(); for (String key : set) { list2.add(map.get(key) == null ? "" : map.get(key) + ""); } listData.add(list2); } // 创建excel工作簿 Workbook wb = new HSSFWorkbook(); // 创建第一个sheet(页),并命名 Sheet sheet = wb.createSheet("数据"); // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。 /* * for(int i=0;i<keys.length;i++){ sheet.setColumnWidth((short) i, * (short) (35.7 * 150)); } */ // 创建第一行 Row row = sheet.createRow((short) 0); // 创建两种单元格格式 CellStyle cs = wb.createCellStyle(); CellStyle cs2 = wb.createCellStyle(); // 创建两种字体 Font f = wb.createFont(); Font f2 = wb.createFont(); // 创建第一种字体样式(用于列名) f.setFontHeightInPoints((short) 10); f.setColor(IndexedColors.BLACK.getIndex()); f.setBoldweight(Font.BOLDWEIGHT_BOLD); // 创建第二种字体样式(用于值) f2.setFontHeightInPoints((short) 10); f2.setColor(IndexedColors.BLACK.getIndex()); // Font f3=wb.createFont(); // f3.setFontHeightInPoints((short) 10); // f3.setColor(IndexedColors.RED.getIndex()); // 设置第一种单元格的样式(用于列名) cs.setFont(f); cs.setBorderLeft(CellStyle.BORDER_THIN); cs.setBorderRight(CellStyle.BORDER_THIN); cs.setBorderTop(CellStyle.BORDER_THIN); cs.setBorderBottom(CellStyle.BORDER_THIN); cs.setAlignment(CellStyle.ALIGN_CENTER); // 设置第二种单元格的样式(用于值) cs2.setFont(f2); cs2.setBorderLeft(CellStyle.BORDER_THIN); cs2.setBorderRight(CellStyle.BORDER_THIN); cs2.setBorderTop(CellStyle.BORDER_THIN); cs2.setBorderBottom(CellStyle.BORDER_THIN); cs2.setAlignment(CellStyle.ALIGN_CENTER); // 设置列名 for (int i = 0; i < listMap.size(); i++) { Cell cell = row.createCell(i); cell.setCellValue(listMap.get(i)); cell.setCellStyle(cs); } // 设置每行每列的值 for (int i = 0; i < listData.size(); i++) { // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的 // 创建一行,在页sheet上 Row row1 = sheet.createRow(i + 1); // 在row行上创建一个方格 for (int j = 0; j < listData.get(i).size(); j++) { Cell cell = row1.createCell(j); String value = listData.get(i).get(j) == null ? "" : (String) listData.get(i).get(j); cell.setCellValue(value); cell.setCellStyle(cs2); } } return wb; } /** * 通过模板导出数据 * * @param listMap * 表头 * @param dataList * 数据 * @param columnNames * excel的列名 * @throws IOException * */ public static Workbook createWorkBookByMouduel(String filePath, List<Map<String, Object>> dataList) throws IOException { // 数据 List<List<String>> listData = new ArrayList<List<String>>();// 将数据装成list<list<>> // 形式 for (int i = 0; i < dataList.size(); i++) { Map<String, Object> map = dataList.get(i); Set<String> set = map.keySet(); List<String> list2 = new ArrayList<String>(); for (String key : set) { list2.add(map.get(key) == null ? "" : map.get(key) + ""); } listData.add(list2); } // 创建excel工作簿 InputStream in = new FileInputStream(new java.io.File(filePath)); Workbook wb = new HSSFWorkbook(in); Sheet sheet = wb.getSheetAt(0); // 创建单元格格式 CellStyle cs2 = wb.createCellStyle(); // 创建字体格式 Font f2 = wb.createFont(); // 创建第二种字体样式(用于值) f2.setFontHeightInPoints((short) 10); f2.setColor(IndexedColors.BLACK.getIndex()); // Font f3=wb.createFont(); // f3.setFontHeightInPoints((short) 10); // f3.setColor(IndexedColors.RED.getIndex()); // 设置第二种单元格的样式(用于值) cs2.setFont(f2); cs2.setBorderLeft(CellStyle.BORDER_THIN); cs2.setBorderRight(CellStyle.BORDER_THIN); cs2.setBorderTop(CellStyle.BORDER_THIN); cs2.setBorderBottom(CellStyle.BORDER_THIN); cs2.setAlignment(CellStyle.ALIGN_CENTER); // 设置每行每列的值 int totalRow = sheet.getLastRowNum(); for (int i = 0; i < listData.size(); i++) { // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的 // 创建一行,在页sheet上 Row row1 = sheet.createRow(i + totalRow + 1); // 在row行上创建一个方格 for (int j = 0; j < listData.get(i).size(); j++) { Cell cell = row1.createCell(j); String value = listData.get(i).get(j) == null ? "" : (String) listData.get(i).get(j); cell.setCellValue(value); cell.setCellStyle(cs2); } } return wb; } /** * @Description 获取cell中的值 * @author 张洋 * @date 2017年4月7日 下午3:48:59 * @param cell * @return */ public static String getValue(Cell cell) { String value = ""; if (null == cell) { return value; } switch (cell.getCellType()) { // 数值型 case Cell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值 Date date = HSSFDateUtil .getJavaDate(cell.getNumericCellValue()); SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); value = format.format(date); ; } else {// 纯数字 BigDecimal big = new BigDecimal(cell.getNumericCellValue()); value = big.toString(); // 解决1234.0 去掉后面的.0 if (null != value && !"".equals(value.trim())) { String[] item = value.split("[.]"); if (1 < item.length && "0".equals(item[1])) { value = item[0]; } } } break; // 字符串类型 case Cell.CELL_TYPE_STRING: value = cell.getStringCellValue().toString(); break; // 公式类型 case Cell.CELL_TYPE_FORMULA: // 读公式计算值 value = String.valueOf(cell.getNumericCellValue()); if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串 value = cell.getStringCellValue().toString(); } break; // 布尔类型 case Cell.CELL_TYPE_BOOLEAN: value = " " + cell.getBooleanCellValue(); break; // 空值 case Cell.CELL_TYPE_BLANK: value = ""; // LogUtil.getLogger().error("excel出现空值"); break; // 故障 case Cell.CELL_TYPE_ERROR: value = ""; // LogUtil.getLogger().error("excel出现故障"); break; default: value = cell.getStringCellValue().toString(); } if ("null".endsWith(value.trim())) { value = ""; } return value; } }
4.导入excell
/** * @Description 导入数据 * @author 张洋 * @date 2017年4月5日 上午10:44:24 * @param param * @param request * @param response * @return * @throws ParseException * @throws IOException * @throws Exception */ @Override public ReturnBean<Map<String, Object>> upload(Map<String, Object> param, HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException { ReturnBean<Map<String, Object>> returnBean = new ReturnBean<Map<String, Object>>(); multipartRequest = (MultipartHttpServletRequest) request; // 得到上传的文件 mFiles = multipartRequest.getFiles("file"); String corpId = (String) request.getSession().getAttribute("corpId"); if (mFiles != null && mFiles.size() > 0) { MultipartFile mFile = mFiles.get(0); List<RiskEnvironment> listData = new ArrayList<RiskEnvironment>();// 所有添加的数据 InputStream fileIn = mFile.getInputStream(); // 根据指定的文件输入流导入Excel从而产生Workbook对象 Workbook wb0 = new HSSFWorkbook(fileIn); // 获取Excel文档中的第一个表单 Sheet sht0 = wb0.getSheetAt(0); if (sht0.getPhysicalNumberOfRows() <= 3) { fileIn.close(); returnBean.setErrorInfo("Excell中无数据"); returnBean.setReturnCode(ReturnCode.EXCELL_DATA_NULL_ERROR); return returnBean; } if (sht0.getRow(0).getPhysicalNumberOfCells() != 21) { fileIn.close(); returnBean.setErrorInfo("Excell格式与模板不符"); returnBean.setReturnCode(ReturnCode.EXCELL_MOUDUEL_ERROR); return returnBean; } // 对Sheet中的每一行进行迭代 List<Map<String, String>> listError = new ArrayList<Map<String, String>>(); for (Row r : sht0) {// 如果当前行的行号(从0开始)未达到2(第三行)则从新循环 if (r.getRowNum() < 3) { continue; } // 创建实体类 RiskEnvironment healthRisk = new RiskEnvironment(); // 取出当前行第1个单元格数据,并封装在info实体stuName属性上 healthRisk.setCorpId(corpId);// 公司id healthRisk.setId(Utils.randomUUID()); healthRisk.setCreateTime(new Timestamp(System .currentTimeMillis())); healthRisk.setSort(this.getSort()); User user = (User) request.getSession() .getAttribute("userInfo"); healthRisk.setCreateUid(user.getId()); healthRisk.setTouchTime1(""); healthRisk.setNote(""); healthRisk.setType(""); deptService.selectByCondition(param); // healthRisk.setDeptId(user.getDeptId()); healthRisk.setState("0"); // 赋值 int i = 0; if (Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) {// 部门填写id healthRisk.setType(ExcelUtil.getValue(r.getCell(i))); listError.add(FileDataUtil.getErrorMap("必填项", r.getRowNum(), i, "")); } else { String deptId = ExcelUtil.getValue(r.getCell(i)); Dept dept = deptService.selectById(deptId); if (dept == null) { listError.add(FileDataUtil.getErrorMap("数据错误", r.getRowNum(), i, "")); } else { healthRisk.setDeptId(deptId); } } ; i++; if (Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) {// 区域填写id(逗号分隔) healthRisk.setType(ExcelUtil.getValue(r.getCell(i))); listError.add(FileDataUtil.getErrorMap("必填项", r.getRowNum(), i, "")); } else { String district = ExcelUtil.getValue(r.getCell(i)); String[] districts = district.split(";"); for (int j = 0; j < districts.length; j++) { DictionaryData dictionary = dictService .selectById(districts[j]); if (dictionary == null) { listError.add(FileDataUtil.getErrorMap("数据错误", r.getRowNum(), i, "")); } } healthRisk.setDistrict(district.replaceAll(";",",")); } i++; if (Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) {// 危害类别id healthRisk.setTypeHarm(ExcelUtil.getValue(r.getCell(i))); listError.add(FileDataUtil.getErrorMap("必填项", r.getRowNum(), i, "")); } else { String typeHarm = ExcelUtil.getValue(r.getCell(i)); DictionaryData dictionary = dictService .selectById(typeHarm); if (dictionary == null) { listError.add(FileDataUtil.getErrorMap("数据错误", r.getRowNum(), i, "")); } else { healthRisk .setTypeHarm(ExcelUtil.getValue(r.getCell(i))); } } i++; if (Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) {// 危害因素id healthRisk.setTypeHarm(ExcelUtil.getValue(r.getCell(i))); listError.add(FileDataUtil.getErrorMap("必填项", r.getRowNum(), i, "")); } else { String typeHarm = ExcelUtil.getValue(r.getCell(i)); DictionaryData dictionary = dictService .selectById(typeHarm); if (dictionary == null) { listError.add(FileDataUtil.getErrorMap("数据错误", r.getRowNum(), i, "")); } else { healthRisk.setHarmElement(ExcelUtil.getValue(r .getCell(i))); } } ; i++; if (Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) {// 危害分布、特性及生产风险条件 healthRisk.setHarmRequirement(ExcelUtil.getValue(r .getCell(i))); listError.add(FileDataUtil.getErrorMap("必填项", r.getRowNum(), i, "")); } else { healthRisk.setHarmRequirement(ExcelUtil.getValue(r .getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setConsequence(ExcelUtil.getValue(r.getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setHarmKind(ExcelUtil.getValue(r.getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setHarmScop(ExcelUtil.getValue(r.getCell(i))); } i++; healthRisk.setPersonOtherInfo(ExcelUtil.getValue(r.getCell(i))); i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setControlMeasures(ExcelUtil.getValue(r .getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { String resultValue = ExcelUtil.getValue(r.getCell(i)); if (RegexUtils.checkInteger(resultValue) || RegexUtils.checkFload(resultValue)) { healthRisk.setResultValue(resultValue); } else { listError.add(FileDataUtil.getErrorMap("格式错误", r.getRowNum(), i, "1,2,3")); } } ; i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { String expose = ExcelUtil.getValue(r.getCell(i)); if (RegexUtils.checkInteger(expose) || RegexUtils.checkFload(expose)) { healthRisk.setExpose(expose); } else { listError.add(FileDataUtil.getErrorMap("格式错误", r.getRowNum(), i, "1,2,3")); } } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { String possibility = ExcelUtil.getValue(r.getCell(i)); if (RegexUtils.checkInteger(possibility) || RegexUtils.checkFload(possibility)) { healthRisk.setPossibility(possibility); } else { listError.add(FileDataUtil.getErrorMap("格式错误", r.getRowNum(), i, "1,2,3")); } } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { String riskValue = ExcelUtil.getValue(r.getCell(i)); if (RegexUtils.checkInteger(riskValue) || RegexUtils.checkFload(riskValue)) { healthRisk .setRiskValue(ExcelUtil.getValue(r.getCell(i))); } else { listError.add(FileDataUtil.getErrorMap("格式错误", r.getRowNum(), i, "1,2,3")); } } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setRiskLevel(ExcelUtil.getValue(r.getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk .setAcceptMeasure(ExcelUtil.getValue(r.getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setMeasureValidity(ExcelUtil.getValue(r .getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setMeasureCost(ExcelUtil.getValue(r.getCell(i))); } i++; if (!Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk .setMeasureResult(ExcelUtil.getValue(r.getCell(i))); } i++; if (Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setTakeIsno("0");// } else { if ("是".equals(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setTakeIsno("1"); } else if ("否".equals(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setTakeIsno("0"); } else { listError.add(FileDataUtil.getErrorMap("格式错误", r.getRowNum(), i, "格式:是或否")); // healthRisk.setTakeIsno(r.getCell(i))); } } i++; if (Utils.isEmpty(ExcelUtil.getValue(r.getCell(i)))) { healthRisk.setAnalysisState("0"); } else { if (RegexUtils.checkDay(ExcelUtil.getValue(r.getCell(i)))) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse(ExcelUtil.getValue(r.getCell(i))); healthRisk .setAnalysisDate(new Timestamp(date.getTime())); healthRisk.setAnalysisState("1"); } else { listError .add(FileDataUtil.getErrorMap("格式错误", r.getRowNum(), i, "格式:yyyy-MM-dd HH:mm:ss(例:2008-01-01 13:00:00)")); } } listData.add(healthRisk); } fileIn.close(); if (listError.size() > 0) { returnBean.setReturnCode(ReturnCode.EXCELL_UPLOAD_ERROR); returnBean.setErrorInfo(listError); } else { if (environmentRiskDao.insertList(listData) > 0) { returnBean.setReturnCode(ReturnCode.SUCCESS); } ; } } return returnBean; }
作者:逆舟
https://www.cnblogs.com/zy-jiayou/
本博客文章均为作者原创,转载请注明作者和原文链接。
https://www.cnblogs.com/zy-jiayou/
本博客文章均为作者原创,转载请注明作者和原文链接。