zoukankan      html  css  js  c++  java
  • poi excel文件上传并解析xls文件

    1.jsp页面

    <form action="hw/pe_xls_upload" method="post" enctype="multipart/form-data" >
        <table>
            <tr>
                <td>导入硬件序列号/密码Excel文件:</td>
                <td><input name="hwFile" type="file"/>&nbsp;&nbsp;</td> <!-- style=" 400px;height: 25px;" -->
                <td><input type="submit" value="上传导入并激活" onclick="javascript:layer.alert('正在处理中', 16);"/></td>
            </tr>
        </table>
        </form>

    2.controller控制器

    @RequestMapping("pe_xls_upload")
        public String hwXlsUpload(@RequestParam("hwFile") MultipartFile hwFile, HttpServletRequest request){
            String msg = "";
            if(!hwFile.isEmpty()){
                String fileType = hwFile.getContentType();
                System.err.println("fileType:" + fileType);
                if(!fileType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") && !fileType.equals("application/vnd.ms-excel") ){
                    logger.error("上传文件类型错误!fileType:{}", fileType);
                    msg = "上传文件类型错误";
                }else{
                    try{
                        String basePath = SysConf.CON_IMAGE_DIR + "upload/";
                        java.io.File dir = new java.io.File(basePath);
                        if(!dir.exists()){
                            dir.mkdir();
                        }
                        String fileName = basePath + hwFile.getOriginalFilename();
                        File file = new File(fileName);
                        FileUtils.writeByteArrayToFile(file, hwFile.getBytes());
                        if(file.exists()){
                            //Excel文件操作
                            Map<String, String> map = null;
                            map = CarHwXls.readXls(fileName);
                            /*for (Map.Entry<String, String> entry : map.entrySet()){
                                System.err.println("$$entry.getKey():" + entry.getKey() + " --- " + entry.getValue());
                            }*/
                            
                            //1.硬件导入和激活
                            CarHwApiNew.insertHwPsw(map);
                            //2.硬件导入和激活
                            CarHwApiNew.activeHwCar();
                            
                            msg = "文件上传成功,并导入和激活设备序列号和密码信息成功完成";
                        }else{
                            msg = "文件上传失败";
                        }
                    }catch(Exception e){
                        logger.error("添加硬件设备号:", e);
                        msg = e.getMessage();
                    }
                }
            }else{
                msg = "请选择上传文件";
            }
            
            request.setAttribute("msg", msg);
            queryHwList(new CarHwSearchBean(),request);
            
            return "hw/list";
        }

    3.xls工具类

    public class CarHwXls {
        private static Logger logger = LoggerFactory.getLogger(CarHwXls.class);
        
        /**
         * 读取xls文件内容
         * 
         * @return List<XlsDto>对象
         * @throws IOException
         *             输入/输出(i/o)异常
         */
        public static Map<String, String> readXls(String xlspath) throws IOException {
            Map<String, String> map = new HashMap<String, String>();
            /** 检查文件名是否为空或者是否是Excel格式的文件 */   
            if (xlspath == null || !(WDWUtil.isExcel2003(xlspath) || WDWUtil.isExcel2007(xlspath)))  
            {  
                logger.info("文件名不是excel格式");
                map.put("msg", "文件名不是excel格式");
                return map;  
            }  
      
            /** 检查文件是否存在 */  
            File file = new File(xlspath);  
            if (file == null || !file.exists())  
            {  
                logger.info("文件不存在");
                map.put("msg", "文件不存在");
                return map; 
            }  
            
            InputStream is = new FileInputStream(xlspath);
    //        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
            /** 根据版本选择创建Workbook的方式 */  
            
            Workbook wb = null;  
    
            if (WDWUtil.isExcel2003(xlspath))  
            {  
                wb = new HSSFWorkbook(is);  
            }  
            else  
            {  
                wb = new XSSFWorkbook(is);  
            }  
            
    //        CellStyle cellStyle = wb.createCellStyle(); 
    //        DataFormat format = wb.createDataFormat(); 
    //        cellStyle.setDataFormat(format.getFormat("@"));
            
            
            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
                Sheet sheet = wb.getSheetAt(numSheet);   //HSSF
    //            System.out.println("sheet:" + sheet);
                if (sheet == null) {
                    continue;
                }
                // 循环行Row,从第一行开始。
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    Row row = sheet.getRow(rowNum);  //HSSF
    //                System.out.println("row:"+row);
                    if (row == null) {
                        continue;
                    }
                    // 循环列Cell
                    // 0学号 1姓名 2学院 3课程名 4 成绩
                    // for (int cellNum = 0; cellNum <=4; cellNum++) {
                    Cell cell0 = row.getCell(0);  //HSSF
    //                cell0.setCellStyle(cellStyle);  //设置为文本型
    //                System.out.println("@@cell0:" + getValue(cell0));
                    if (cell0 == null || !getValue(cell0).startsWith("96779")) {   //不已96779开头的记录。  
                        continue;
                    }
                    
                    
                    Cell cell1 = row.getCell(1);  //HSSF
    //                cell1.setCellStyle(cellStyle);  //设置为文本型
    //                System.out.println("$$cell1:" + getValue(cell1));
                    if (cell1 == null || getValue(cell1).length() != 8) {
                        continue;
                    }
                   
                    
                    map.put(getValue(cell0), getValue(cell1));
                }
            }
    //        System.out.println("SIZE:" + list.size());
            return map;
        }
    
        /**
         * 得到Excel表中的值
         * 
         * @param hssfCell
         *            Excel中的每一个格子
         * @return Excel中每一个格子中的值
         */
        @SuppressWarnings("static-access")
        public static String getValue(Cell cell) {  //HSSF
            /*if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
                // 返回布尔类型的值
                return String.valueOf(cell.getBooleanCellValue());
            } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
                // 返回数值类型的值
                return String.valueOf(cell.getNumericCellValue());
            } else {
                // 返回字符串类型的值
                return String.valueOf(cell.getStringCellValue());
            }*/
            String cellValue = "";
            if (null != cell)  
            {  
                // 以下是判断数据的类型  
                switch (cell.getCellType())  
                {  
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字  
    //                cellValue = cell.getNumericCellValue() + "";  
                    DecimalFormat df = new DecimalFormat("0");     //避免科学计数法显示。
                    cellValue = df.format(cell.getNumericCellValue());  
                    
    //                cellValue = cell.getStringCellValue();  
                    break;  
    
                case HSSFCell.CELL_TYPE_STRING: // 字符串  
                    cellValue = cell.getStringCellValue();  
                    break;  
    
                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean  
                    cellValue = cell.getBooleanCellValue() + "";  
                    break;  
    
                case HSSFCell.CELL_TYPE_FORMULA: // 公式  
                    cellValue = cell.getCellFormula() + "";  
                    break;  
    
                case HSSFCell.CELL_TYPE_BLANK: // 空值  
                    cellValue = "";  
                    break;  
    
                case HSSFCell.CELL_TYPE_ERROR: // 故障  
                    cellValue = "非法字符";  
                    break;  
    
                default:  
                    cellValue = "未知类型";  
                    break;  
                }  
            }  
            return cellValue;
            
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Map<String, String> map = null;
            try {
                map = CarHwXls.readXls("d://硬件号.xlsx");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            for (Map.Entry<String, String> entry : map.entrySet()){
                System.err.println("entry.getKey():" + entry.getKey() + " --- " + entry.getValue());
            }
        }
    
    }
    
    class WDWUtil  
    {  
        /** 
         * @描述:是否是2003的excel,返回true是2003 
         * @参数:@param filePath 文件完整路径 
         * @参数:@return 
         * @返回值:boolean 
         */
        public static boolean isExcel2003(String filePath)  
        {  
            return filePath.matches("^.+\.(?i)(xls)$");  
        }  
      
        
        /** 
         * @描述:是否是2007的excel,返回true是2007 
         * @参数:@param filePath 文件完整路径 
         * @参数:@return 
         * @返回值:boolean 
         */  
        public static boolean isExcel2007(String filePath)  
        {  
            return filePath.matches("^.+\.(?i)(xlsx)$");  
        }
    }  
  • 相关阅读:
    使用IDEA整合SSM框架
    宏任务与微任务
    setTimeout的实现及其问题
    JS的闭合(Closure)
    this详解
    JS的作用域和作用域链
    JS的执行上下文
    JS内存机制
    抽象工厂模式(c++实现)
    迭代器模式(c++实现)
  • 原文地址:https://www.cnblogs.com/simpledev/p/3956921.html
Copyright © 2011-2022 走看看