ssh框架POi导入excel表格兼容excel2003和2007版本

来源:互联网 发布:天勤网络 编辑:程序博客网 时间:2024/05/16 06:12

1、首先是页面,简单的上传控件,这个大家应该都会,不做详细阐述了。

<div class="control-group"> <label class="control-label " style="margin-left: 16px;">选择上传文件:</label> <div class="controls" id="uploadExcel">   <input id="carNoExcel" required="required" name="carNoExcel" type="file" size="40" accept=".xls,.xlsx"><br> </div></div>
function importE(){    //获取Excel文件名FileNmae,并作为参数跳转   if(checkFile()){  /*  var fileName=document.getElementById("carNoExcel").value;   var fileName = getFileName(fileName);   $("#uploadExcel").append('<input id="fileName" name="fileName" type="hidden" size="40" value="'+fileName+'">'      );  */   loadingShow();   window.ImportForm.action = "analysis_importCarNo.do";   window.ImportForm.submit();   }  } 

2、struts2的好处是能获取到上传控件的文件名,直接定义文件名,加上get、set方法即可获得。

private String carNoExcelFileName;  //可以获取上传文件名public String getCarNoExcelFileName() {return carNoExcelFileName;}public void setCarNoExcelFileName(String carNoExcelFileName) {this.carNoExcelFileName = carNoExcelFileName;}

3、接下来是导入的方法

public String importCarNo() throws Exception {// 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全String savePath = ServletActionContext.getServletContext().getRealPath("/excel");// 获取Jsp页面传来的文件虚拟路径,文件上传是,系统会在文件名的前面加上虚拟路径,如:C:/path/example.xls//System.out.println("carNoExcelFileName:"+carNoExcelFileName);String temp[] = carNoExcelFileName.split("\\\\");if (temp.length > 1) {// 将反斜杠去除carNoExcelFileName = temp[temp.length - 1];}if (carNoExcel != null) {// 创建保存在服务器文件,以FileName命名File savefile = new File(new File(savePath), carNoExcelFileName);if (!savefile.getParentFile().exists())savefile.getParentFile().mkdirs();try {FileUtils.copyFile(carNoExcel, savefile);} catch (IOException e) {e.printStackTrace();}}// 获取文件路径String filePath = savePath + "\\" + carNoExcelFileName;try {// 读取excel表格ExcelImport excelImport = new ExcelImport(filePath);List<CarNoInfo> importList = excelImport.readExcel();infolist = new ArrayList<CarNoInfo>();for (CarNoInfo carNoInfo : importList) {requestData(carNoInfo);}ActionContext.getContext().getSession().put("infolist", infolist);ActionContext.getContext().getSession().put("flag", "2");} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}ActionContext.getContext().put("message", "文件导入成功");return "importCarNoJsp";}

4、表格处理类

public class ExcelImport {    private Workbook hssfWB = null;    InputStream read = null;    OutputStream write = null;    private String file;    public ExcelImport(){}    /**     * 初始化文件,判断文件情况     * 找到合适的类型控制     * @param file     * @throws Exception      */    public ExcelImport(String file) throws Exception{        this.file = file;        read = null;        if(file==null||"".equals(file)){            System.out.println("文件不能为空!");            throw new Exception();        }        try {            read = new FileInputStream(file);        } catch (FileNotFoundException e) {            System.out.println("文件路径不正确!");            e.printStackTrace();        }        try{            if(file.endsWith(".xls")||file.endsWith(".xlsx")){            hssfWB= WorkbookFactory.create(read);            }else{                System.out.println("文件格式不正确!");                ActionContext.getContext().put("message", "文件格式不正确!");                throw new IOException();            }        }catch(IOException e){            System.out.println("文件已损坏或者未知原因!");            ActionContext.getContext().put("message", "文件已损坏或者未知原因!!");            e.printStackTrace();        }    }    /**     * 读取Excel;     * @return     */    public List<CarNoInfo> readExcel(){    List<CarNoInfo> list = new ArrayList<CarNoInfo>();        if(hssfWB!=null){            list = this.readExcel();        }        this.free();        return list;    }    /**     * 释放IO流     * 减少内存损耗     */    private void free(){        try{            if(read!=null){                read.close();            }            if(write!=null){                write.close();            }        }catch(IOException e){            e.printStackTrace();        }    }    /**     * 私有化读取2003、2007版本Excel     * @return     */private List<CarNoInfo> readExcel(){        List<CarNoInfo> list = new ArrayList<CarNoInfo>();        //获取表里的第一个工作蒲        Row row;        Cell cell;        Sheet sheet = hssfWB.getSheetAt(0);        if(sheet.getPhysicalNumberOfRows()>0){            //从Excel表格第1行开始读取        for(int i=2;i<sheet.getPhysicalNumberOfRows();i++){              CarNoInfo carNoInfo=new CarNoInfo();              row = sheet.getRow(i);               for(int j=0;j<row.getLastCellNum();j++){                  cell = row.getCell(j);                  Object cellValue=null;                  cellValue=getCellValue(cell);                  switch (j) {        case 0:carNoInfo.setCarNo(String.valueOf(cellValue));break;case 1:carNoInfo.setColor(String.valueOf(cellValue));break;default:break;}                }                list.add(carNoInfo);            }        }else{            System.out.println("文件中没有数据!");        }        return list;    }/**     * 获取单元格格式     */    private static Object getCellValue(Cell cell) {         Object obj = null;         if(cell == null) return null;         switch (cell.getCellType()) {             case Cell.CELL_TYPE_STRING:                 obj = cell.getRichStringCellValue().getString().trim();                 break;             case Cell.CELL_TYPE_NUMERIC:                 if (DateUtil.isCellDateFormatted(cell)) {                     obj = cell.getDateCellValue();                }else {                     NumberFormat nf = NumberFormat.getInstance();                    nf.setGroupingUsed(false);                    obj = nf.format(cell.getNumericCellValue());                 }                 break;             case Cell.CELL_TYPE_BOOLEAN:                 obj =  cell.getBooleanCellValue();                 break;             case Cell.CELL_TYPE_FORMULA:                 obj = cell.getCellFormula();                 break;             default:         }         return obj;      }}

原创粉丝点击