POI 导入导出Excel文件到数据库(转载)

来源:互联网 发布:数据之魅 pdf 编辑:程序博客网 时间:2024/06/05 23:59

1.导入相应的poi jar包,我用的是3.7;

 

2.导入Excel文件到数据的类(这里我把解析Excel文件的操作封装成一个类,在action中只要调用该类就可以了):

Java代码
  1. /**  
  2.      * POI:解析Excel文件中的数据并把每行数据封装成一个实体  
  3.      * @param fis 文件输入流  
  4.      * @return List<EmployeeInfo> Excel中数据封装实体的集合  
  5.      */  
  6.     public static List<EmployeeInfo> importEmployeeByPoi(InputStream fis) {   
  7.            
  8.         List<EmployeeInfo> infos = new ArrayList<EmployeeInfo>();   
  9.         EmployeeInfo employeeInfo = null;   
  10.            
  11.         try {   
  12.             //创建Excel工作薄   
  13.             HSSFWorkbook hwb = new HSSFWorkbook(fis);   
  14.             //得到第一个工作表   
  15.             HSSFSheet sheet = hwb.getSheetAt(0);   
  16.             HSSFRow row = null;   
  17.             //日期格式化   
  18.             DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");   
  19.             //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数    
  20.             for(int i = 0; i < hwb.getNumberOfSheets(); i++) {   
  21.                 sheet = hwb.getSheetAt(i);   
  22.                 //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数   
  23.                 for(int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {   
  24.                     row = sheet.getRow(j);   
  25.                     employeeInfo = new EmployeeInfo();   
  26.                        
  27.                     /*此方法规定Excel文件中的数据必须为文本格式,所以在解析数据的时候未进行判断  
  28.                     //方法1:Excel解析出来的数字为double类型,要转化为Long类型必须做相应的处理(一开始用的方法,比较笨。) 
  29.                     //先把解析出来的double类型转化为String类型,然后截取String类型'.'以前的字符串,最后把字符串转化为Long类型。  
  30.                     String orgId = row.getCell(0).toString();  
  31.                     String orgId1 = orgId.substring(0, orgId.indexOf('.'));  
  32.                     //方法2:其实double类型可以通过(long)Double这样直接转化为Long类型。  
  33.                     employeeInfo.setOrgId((long)(row.getCell(0).getNumericCellValue()));  
  34.                     employeeInfo.setEmployeeNumber(row.getCell(1).toString());  
  35.                     employeeInfo.setFullName(row.getCell(2).toString());  
  36.                     employeeInfo.setSex(row.getCell(3).toString());  
  37.                     if(row.getCell(4) != null) {  
  38.                         try {  
  39.                             employeeInfo.setDateOfBirth(ft.parse(row.getCell(4).toString()));  
  40.                         } catch (ParseException e) {  
  41.                             e.printStackTrace();  
  42.                         }  
  43.                     }  
  44.                     employeeInfo.setTownOfBirth(row.getCell(5).toString());  
  45.                     employeeInfo.setNationalIdentifier(row.getCell(6).toString());*/  
  46.                        
  47.                     //此方法调用getCellValue(HSSFCell cell)对解析出来的数据进行判断,并做相应的处理   
  48.                     if(ImportEmployee.getCellValue(row.getCell(0)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(0)))) {   
  49.                         employeeInfo.setOrgId(Long.valueOf(ImportEmployee.getCellValue(row.getCell(0))));   
  50.                     }   
  51.                     employeeInfo.setEmployeeNumber(ImportEmployee.getCellValue(row.getCell(1)));   
  52.                     employeeInfo.setFullName(ImportEmployee.getCellValue(row.getCell(2)));   
  53.                     employeeInfo.setSex(ImportEmployee.getCellValue(row.getCell(3)));   
  54.                     if(ImportEmployee.getCellValue(row.getCell(4)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(4)))) {   
  55.                         try {   
  56.                             employeeInfo.setDateOfBirth(ft.parse(ImportEmployee.getCellValue(row.getCell(4))));   
  57.                         } catch (ParseException e) {   
  58.                             e.printStackTrace();   
  59.                         }   
  60.                         employeeInfo.setTownOfBirth(ImportEmployee.getCellValue(row.getCell(5)));   
  61.                     }   
  62.                     employeeInfo.setNationalIdentifier(ImportEmployee.getCellValue(row.getCell(6)));   
  63.                     infos.add(employeeInfo);   
  64.                 }   
  65.                    
  66.             }   
  67.         } catch (IOException e) {   
  68.             e.printStackTrace();   
  69.         }   
  70.         return infos;   
  71.     }   
  72.     //判断从Excel文件中解析出来数据的格式   
  73.     private static String getCellValue(HSSFCell cell){   
  74.         String value = null;   
  75.         //简单的查检列类型   
  76.         switch(cell.getCellType())   
  77.         {   
  78.             case HSSFCell.CELL_TYPE_STRING://字符串   
  79.                 value = cell.getRichStringCellValue().getString();   
  80.                 break;   
  81.             case HSSFCell.CELL_TYPE_NUMERIC://数字   
  82.                 long dd = (long)cell.getNumericCellValue();   
  83.                 value = dd+"";   
  84.                 break;   
  85.             case HSSFCell.CELL_TYPE_BLANK:   
  86.                 value = "";   
  87.                 break;      
  88.             case HSSFCell.CELL_TYPE_FORMULA:   
  89.                 value = String.valueOf(cell.getCellFormula());   
  90.                 break;   
  91.             case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值   
  92.                 value = String.valueOf(cell.getBooleanCellValue());   
  93.                 break;   
  94.             case HSSFCell.CELL_TYPE_ERROR:   
  95.                 value = String.valueOf(cell.getErrorCellValue());   
  96.                 break;   
  97.             default:   
  98.                 break;   
  99.         }   
  100.         return value;   
  101.     }  
[java] view plaincopyprint?
  1. /** 
  2.      * POI:解析Excel文件中的数据并把每行数据封装成一个实体 
  3.      * @param fis 文件输入流 
  4.      * @return List<EmployeeInfo> Excel中数据封装实体的集合 
  5.      */  
  6.     public static List<EmployeeInfo> importEmployeeByPoi(InputStream fis) {  
  7.           
  8.         List<EmployeeInfo> infos = new ArrayList<EmployeeInfo>();  
  9.         EmployeeInfo employeeInfo = null;  
  10.           
  11.         try {  
  12.             //创建Excel工作薄   
  13.             HSSFWorkbook hwb = new HSSFWorkbook(fis);  
  14.             //得到第一个工作表   
  15.             HSSFSheet sheet = hwb.getSheetAt(0);  
  16.             HSSFRow row = null;  
  17.             //日期格式化   
  18.             DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");  
  19.             //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数    
  20.             for(int i = 0; i < hwb.getNumberOfSheets(); i++) {  
  21.                 sheet = hwb.getSheetAt(i);  
  22.                 //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数   
  23.                 for(int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {  
  24.                     row = sheet.getRow(j);  
  25.                     employeeInfo = new EmployeeInfo();  
  26.                       
  27.                     /*此方法规定Excel文件中的数据必须为文本格式,所以在解析数据的时候未进行判断 
  28.                     //方法1:Excel解析出来的数字为double类型,要转化为Long类型必须做相应的处理(一开始用的方法,比较笨。) 
  29.                     //先把解析出来的double类型转化为String类型,然后截取String类型'.'以前的字符串,最后把字符串转化为Long类型。 
  30.                     String orgId = row.getCell(0).toString(); 
  31.                     String orgId1 = orgId.substring(0, orgId.indexOf('.')); 
  32.                     //方法2:其实double类型可以通过(long)Double这样直接转化为Long类型。 
  33.                     employeeInfo.setOrgId((long)(row.getCell(0).getNumericCellValue())); 
  34.                     employeeInfo.setEmployeeNumber(row.getCell(1).toString()); 
  35.                     employeeInfo.setFullName(row.getCell(2).toString()); 
  36.                     employeeInfo.setSex(row.getCell(3).toString()); 
  37.                     if(row.getCell(4) != null) { 
  38.                         try { 
  39.                             employeeInfo.setDateOfBirth(ft.parse(row.getCell(4).toString())); 
  40.                         } catch (ParseException e) { 
  41.                             e.printStackTrace(); 
  42.                         } 
  43.                     } 
  44.                     employeeInfo.setTownOfBirth(row.getCell(5).toString()); 
  45.                     employeeInfo.setNationalIdentifier(row.getCell(6).toString());*/  
  46.                       
  47.                     //此方法调用getCellValue(HSSFCell cell)对解析出来的数据进行判断,并做相应的处理   
  48.                     if(ImportEmployee.getCellValue(row.getCell(0)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(0)))) {  
  49.                         employeeInfo.setOrgId(Long.valueOf(ImportEmployee.getCellValue(row.getCell(0))));  
  50.                     }  
  51.                     employeeInfo.setEmployeeNumber(ImportEmployee.getCellValue(row.getCell(1)));  
  52.                     employeeInfo.setFullName(ImportEmployee.getCellValue(row.getCell(2)));  
  53.                     employeeInfo.setSex(ImportEmployee.getCellValue(row.getCell(3)));  
  54.                     if(ImportEmployee.getCellValue(row.getCell(4)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(4)))) {  
  55.                         try {  
  56.                             employeeInfo.setDateOfBirth(ft.parse(ImportEmployee.getCellValue(row.getCell(4))));  
  57.                         } catch (ParseException e) {  
  58.                             e.printStackTrace();  
  59.                         }  
  60.                         employeeInfo.setTownOfBirth(ImportEmployee.getCellValue(row.getCell(5)));  
  61.                     }  
  62.                     employeeInfo.setNationalIdentifier(ImportEmployee.getCellValue(row.getCell(6)));  
  63.                     infos.add(employeeInfo);  
  64.                 }  
  65.                   
  66.             }  
  67.         } catch (IOException e) {  
  68.             e.printStackTrace();  
  69.         }  
  70.         return infos;  
  71.     }  
  72.     //判断从Excel文件中解析出来数据的格式   
  73.     private static String getCellValue(HSSFCell cell){  
  74.         String value = null;  
  75.         //简单的查检列类型   
  76.         switch(cell.getCellType())  
  77.         {  
  78.             case HSSFCell.CELL_TYPE_STRING://字符串   
  79.                 value = cell.getRichStringCellValue().getString();  
  80.                 break;  
  81.             case HSSFCell.CELL_TYPE_NUMERIC://数字   
  82.                 long dd = (long)cell.getNumericCellValue();  
  83.                 value = dd+"";  
  84.                 break;  
  85.             case HSSFCell.CELL_TYPE_BLANK:  
  86.                 value = "";  
  87.                 break;     
  88.             case HSSFCell.CELL_TYPE_FORMULA:  
  89.                 value = String.valueOf(cell.getCellFormula());  
  90.                 break;  
  91.             case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值   
  92.                 value = String.valueOf(cell.getBooleanCellValue());  
  93.                 break;  
  94.             case HSSFCell.CELL_TYPE_ERROR:  
  95.                 value = String.valueOf(cell.getErrorCellValue());  
  96.                 break;  
  97.             default:  
  98.                 break;  
  99.         }  
  100.         return value;  
  101.     }  
[java] view plaincopyprint?
  1. <span style="font-size:14px;">/** 
  2.      * POI:解析Excel文件中的数据并把每行数据封装成一个实体 
  3.      * @param fis 文件输入流 
  4.      * @return List<EmployeeInfo> Excel中数据封装实体的集合 
  5.      */  
  6.     public static List<EmployeeInfo> importEmployeeByPoi(InputStream fis) {  
  7.           
  8.         List<EmployeeInfo> infos = new ArrayList<EmployeeInfo>();  
  9.         EmployeeInfo employeeInfo = null;  
  10.           
  11.         try {  
  12.             //创建Excel工作薄  
  13.             HSSFWorkbook hwb = new HSSFWorkbook(fis);  
  14.             //得到第一个工作表  
  15.             HSSFSheet sheet = hwb.getSheetAt(0);  
  16.             HSSFRow row = null;  
  17.             //日期格式化  
  18.             DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");  
  19.             //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数   
  20.             for(int i = 0; i < hwb.getNumberOfSheets(); i++) {  
  21.                 sheet = hwb.getSheetAt(i);  
  22.                 //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数  
  23.                 for(int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {  
  24.                     row = sheet.getRow(j);  
  25.                     employeeInfo = new EmployeeInfo();  
  26.                       
  27.                     /*此方法规定Excel文件中的数据必须为文本格式,所以在解析数据的时候未进行判断 
  28.                     //方法1:Excel解析出来的数字为double类型,要转化为Long类型必须做相应的处理(一开始用的方法,比较笨。) 
  29.                     //先把解析出来的double类型转化为String类型,然后截取String类型'.'以前的字符串,最后把字符串转化为Long类型。 
  30.                     String orgId = row.getCell(0).toString(); 
  31.                     String orgId1 = orgId.substring(0, orgId.indexOf('.')); 
  32.                     //方法2:其实double类型可以通过(long)Double这样直接转化为Long类型。 
  33.                     employeeInfo.setOrgId((long)(row.getCell(0).getNumericCellValue())); 
  34.                     employeeInfo.setEmployeeNumber(row.getCell(1).toString()); 
  35.                     employeeInfo.setFullName(row.getCell(2).toString()); 
  36.                     employeeInfo.setSex(row.getCell(3).toString()); 
  37.                     if(row.getCell(4) != null) { 
  38.                         try { 
  39.                             employeeInfo.setDateOfBirth(ft.parse(row.getCell(4).toString())); 
  40.                         } catch (ParseException e) { 
  41.                             e.printStackTrace(); 
  42.                         } 
  43.                     } 
  44.                     employeeInfo.setTownOfBirth(row.getCell(5).toString()); 
  45.                     employeeInfo.setNationalIdentifier(row.getCell(6).toString());*/  
  46.                       
  47.                     //此方法调用getCellValue(HSSFCell cell)对解析出来的数据进行判断,并做相应的处理  
  48.                     if(ImportEmployee.getCellValue(row.getCell(0)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(0)))) {  
  49.                         employeeInfo.setOrgId(Long.valueOf(ImportEmployee.getCellValue(row.getCell(0))));  
  50.                     }  
  51.                     employeeInfo.setEmployeeNumber(ImportEmployee.getCellValue(row.getCell(1)));  
  52.                     employeeInfo.setFullName(ImportEmployee.getCellValue(row.getCell(2)));  
  53.                     employeeInfo.setSex(ImportEmployee.getCellValue(row.getCell(3)));  
  54.                     if(ImportEmployee.getCellValue(row.getCell(4)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(4)))) {  
  55.                         try {  
  56.                             employeeInfo.setDateOfBirth(ft.parse(ImportEmployee.getCellValue(row.getCell(4))));  
  57.                         } catch (ParseException e) {  
  58.                             e.printStackTrace();  
  59.                         }  
  60.                         employeeInfo.setTownOfBirth(ImportEmployee.getCellValue(row.getCell(5)));  
  61.                     }  
  62.                     employeeInfo.setNationalIdentifier(ImportEmployee.getCellValue(row.getCell(6)));  
  63.                     infos.add(employeeInfo);  
  64.                 }  
  65.                   
  66.             }  
  67.         } catch (IOException e) {  
  68.             e.printStackTrace();  
  69.         }  
  70.         return infos;  
  71.     }  
  72.     //判断从Excel文件中解析出来数据的格式  
  73.     private static String getCellValue(HSSFCell cell){  
  74.         String value = null;  
  75.         //简单的查检列类型  
  76.         switch(cell.getCellType())  
  77.         {  
  78.             case HSSFCell.CELL_TYPE_STRING://字符串  
  79.                 value = cell.getRichStringCellValue().getString();  
  80.                 break;  
  81.             case HSSFCell.CELL_TYPE_NUMERIC://数字  
  82.                 long dd = (long)cell.getNumericCellValue();  
  83.                 value = dd+"";  
  84.                 break;  
  85.             case HSSFCell.CELL_TYPE_BLANK:  
  86.                 value = "";  
  87.                 break;     
  88.             case HSSFCell.CELL_TYPE_FORMULA:  
  89.                 value = String.valueOf(cell.getCellFormula());  
  90.                 break;  
  91.             case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值  
  92.                 value = String.valueOf(cell.getBooleanCellValue());  
  93.                 break;  
  94.             case HSSFCell.CELL_TYPE_ERROR:  
  95.                 value = String.valueOf(cell.getErrorCellValue());  
  96.                 break;  
  97.             default:  
  98.                 break;  
  99.         }  
  100.         return value;  
  101.     }  
  102. </span>  

 action中的写法:

    因为是做练习,只是熟悉它的用法,这里做的比较简单。

Java代码 复制代码 收藏代码
  1. //从页面接收参数:文件的路径   
  2.         String excelPath = request.getParameter("excelPath");   
  3.         //输入流   
  4.         InputStream fis = new FileInputStream(excelPath);   
  5.            
  6.         //JXL:得到解析Excel的实体集合   
  7.         // List<EmployeeInfo> infos = ImportEmployee.importEmployee(fis);   
  8.            
  9.         //POI:得到解析Excel的实体集合   
  10.         List<EmployeeInfo> infos = ImportEmployee.importEmployeeByPoi(fis);   
  11.            
  12.         //遍历解析Excel的实体集合   
  13.         for(EmployeeInfo info:infos) {   
  14.             //判断员工编号是否存在(存在:做修改操作;不存在:做新增操作)   
  15.             EmployeeInfo info1 = this.selectEmpByEmpNum(info.getEmployeeNumber());   
  16.             if(info1 == null) {   
  17.                 //把实体新加到数据库中   
  18.                 this.service.addEmployeeInfo(info);   
  19.             }else{   
  20.                 //把personId封装到实体   
  21.                 info.setPersonId(info1.getPersonId());   
  22.                 //更新实体   
  23.                 this.updatEmployeeInfo(info);   
  24.             }   
  25.         }   
  26.         //关闭流   
  27.         fis.close();  
[java] view plaincopyprint?
  1. //从页面接收参数:文件的路径   
  2.         String excelPath = request.getParameter("excelPath");  
  3.         //输入流   
  4.         InputStream fis = new FileInputStream(excelPath);  
  5.           
  6.         //JXL:得到解析Excel的实体集合   
  7.         // List<EmployeeInfo> infos = ImportEmployee.importEmployee(fis);   
  8.           
  9.         //POI:得到解析Excel的实体集合   
  10.         List<EmployeeInfo> infos = ImportEmployee.importEmployeeByPoi(fis);  
  11.           
  12.         //遍历解析Excel的实体集合   
  13.         for(EmployeeInfo info:infos) {  
  14.             //判断员工编号是否存在(存在:做修改操作;不存在:做新增操作)   
  15.             EmployeeInfo info1 = this.selectEmpByEmpNum(info.getEmployeeNumber());  
  16.             if(info1 == null) {  
  17.                 //把实体新加到数据库中   
  18.                 this.service.addEmployeeInfo(info);  
  19.             }else{  
  20.                 //把personId封装到实体   
  21.                 info.setPersonId(info1.getPersonId());  
  22.                 //更新实体   
  23.                 this.updatEmployeeInfo(info);  
  24.             }  
  25.         }  
  26.         //关闭流   
  27.         fis.close();  
[java] view plaincopyprint?
  1. <span style="font-size:14px;">//从页面接收参数:文件的路径  
  2.         String excelPath = request.getParameter("excelPath");  
  3.         //输入流  
  4.         InputStream fis = new FileInputStream(excelPath);  
  5.           
  6.         //JXL:得到解析Excel的实体集合  
  7.         // List<EmployeeInfo> infos = ImportEmployee.importEmployee(fis);  
  8.           
  9.         //POI:得到解析Excel的实体集合  
  10.         List<EmployeeInfo> infos = ImportEmployee.importEmployeeByPoi(fis);  
  11.           
  12.         //遍历解析Excel的实体集合  
  13.         for(EmployeeInfo info:infos) {  
  14.             //判断员工编号是否存在(存在:做修改操作;不存在:做新增操作)  
  15.             EmployeeInfo info1 = this.selectEmpByEmpNum(info.getEmployeeNumber());  
  16.             if(info1 == null) {  
  17.                 //把实体新加到数据库中  
  18.                 this.service.addEmployeeInfo(info);  
  19.             }else{  
  20.                 //把personId封装到实体  
  21.                 info.setPersonId(info1.getPersonId());  
  22.                 //更新实体  
  23.                 this.updatEmployeeInfo(info);  
  24.             }  
  25.         }  
  26.         //关闭流  
  27.         fis.close();</span>  

 为了整个导入的完整性,最后附上jsp页面的代码:

Java代码 复制代码 收藏代码
  1. <input type="file" id="excelPath" name="excelPath"/>&nbsp;&nbsp;   
  2. <input type="button"  value="导入Excel" onclick="importEmp()"/>   
  3.   
  4. -----------------------JS对导入的文件做简单的判断------------------------   
  5.   
  6. //Excel文件导入到数据库中   
  7. function importEmp(){   
  8.     //检验导入的文件是否为Excel文件   
  9.     var excelPath = document.getElementById("excelPath").value;   
  10.     if(excelPath == null || excelPath == ''){   
  11.         alert("请选择要上传的Excel文件");   
  12.         return;   
  13.     }else{   
  14.         var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();    
  15.         if(fileExtend == '.xls'){   
  16.         }else{   
  17.             alert("文件格式需为'.xls'格式");   
  18.             return;   
  19.         }   
  20.     }   
  21.     //提交表单   
  22.     document.getElementById("empForm").action="<%=request.getContextPath()%>/EmpExcel.action.EmpExcelAction.do?method=importEmployeeInfos";     
  23.     document.getElementById("empForm").submit();   
  24. }  
[java] view plaincopyprint?
  1. <input type="file" id="excelPath" name="excelPath"/>&nbsp;&nbsp;  
  2. <input type="button"  value="导入Excel" onclick="importEmp()"/>  
  3.   
  4. -----------------------JS对导入的文件做简单的判断------------------------  
  5.   
  6. //Excel文件导入到数据库中   
  7. function importEmp(){  
  8.     //检验导入的文件是否为Excel文件   
  9.     var excelPath = document.getElementById("excelPath").value;  
  10.     if(excelPath == null || excelPath == ''){  
  11.         alert("请选择要上传的Excel文件");  
  12.         return;  
  13.     }else{  
  14.         var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();   
  15.         if(fileExtend == '.xls'){  
  16.         }else{  
  17.             alert("文件格式需为'.xls'格式");  
  18.             return;  
  19.         }  
  20.     }  
  21.     //提交表单   
  22.     document.getElementById("empForm").action="<%=request.getContextPath()%>/EmpExcel.action.EmpExcelAction.do?method=importEmployeeInfos";    
  23.     document.getElementById("empForm").submit();  
  24. }  
[java] view plaincopyprint?
  1. <span style="font-size:14px;"><input type="file" id="excelPath" name="excelPath"/>&nbsp;&nbsp;  
  2. <input type="button"  value="导入Excel" onclick="importEmp()"/>  
  3.   
  4. -----------------------JS对导入的文件做简单的判断------------------------  
  5.   
  6. //Excel文件导入到数据库中  
  7. function importEmp(){  
  8.     //检验导入的文件是否为Excel文件  
  9.     var excelPath = document.getElementById("excelPath").value;  
  10.     if(excelPath == null || excelPath == ''){  
  11.         alert("请选择要上传的Excel文件");  
  12.         return;  
  13.     }else{  
  14.         var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();   
  15.         if(fileExtend == '.xls'){  
  16.         }else{  
  17.             alert("文件格式需为'.xls'格式");  
  18.             return;  
  19.         }  
  20.     }  
  21.     //提交表单  
  22.     document.getElementById("empForm").action="<%=request.getContextPath()%>/EmpExcel.action.EmpExcelAction.do?method=importEmployeeInfos";    
  23.     document.getElementById("empForm").submit();  
  24. }</span>  

 到此为止就是导入Excel文件的所有代码。

 

 

3.导出为Excel文件:

Java代码 复制代码 收藏代码
  1. /**  
  2.  * POI : 导出数据,存放于Excel中  
  3.  * @param os 输出流 (action: OutputStream os = response.getOutputStream();)  
  4.  * @param employeeInfos 要导出的数据集合  
  5.  */  
  6. public static void exportEmployeeByPoi(OutputStream os, List<EmployeeInfo> employeeInfos) {   
  7.        
  8.     try {   
  9.         //创建Excel工作薄   
  10.         HSSFWorkbook book = new HSSFWorkbook();   
  11.         //在Excel工作薄中建一张工作表   
  12.         HSSFSheet sheet = book.createSheet("员工信息");   
  13.         //设置单元格格式(文本)   
  14.         //HSSFCellStyle cellStyle = book.createCellStyle();   
  15.         //第一行为标题行   
  16.         HSSFRow row = sheet.createRow(0);//创建第一行   
  17.         HSSFCell cell0 = row.createCell(0);   
  18.         HSSFCell cell1 = row.createCell(1);   
  19.         HSSFCell cell2 = row.createCell(2);   
  20.         HSSFCell cell3 = row.createCell(3);   
  21.         HSSFCell cell4 = row.createCell(4);   
  22.         //定义单元格为字符串类型   
  23.         cell0.setCellType(HSSFCell.CELL_TYPE_STRING);   
  24.         cell1.setCellType(HSSFCell.CELL_TYPE_STRING);   
  25.         cell2.setCellType(HSSFCell.CELL_TYPE_STRING);   
  26.         cell3.setCellType(HSSFCell.CELL_TYPE_STRING);   
  27.         cell4.setCellType(HSSFCell.CELL_TYPE_STRING);   
  28.         //在单元格中输入数据   
  29.         cell0.setCellValue("员工编号");   
  30.         cell1.setCellValue("员工姓名");   
  31.         cell2.setCellValue("员工性别");   
  32.         cell3.setCellValue("出生日期");   
  33.         cell4.setCellValue("身份证号");   
  34.         //循环导出数据到excel中   
  35.         for(int i = 0; i < employeeInfos.size(); i++) {   
  36.             EmployeeInfo employeeInfo = employeeInfos.get(i);   
  37.             //创建第i行   
  38.             HSSFRow rowi = sheet.createRow(i + 1);   
  39.             //在第i行的相应列中加入相应的数据   
  40.             rowi.createCell(0).setCellValue(employeeInfo.getEmployeeNumber());   
  41.             rowi.createCell(1).setCellValue(employeeInfo.getFullName());   
  42.             //处理性别(M:男 F:女)   
  43.             String sex = null;   
  44.             if("M".equals(employeeInfo.getSex())) {   
  45.                 sex = "男";   
  46.             }else {   
  47.                 sex = "女";   
  48.             }   
  49.             rowi.createCell(2).setCellValue(sex);   
  50.             //对日期的处理   
  51.             if(employeeInfo.getDateOfBirth() != null && !"".equals(employeeInfo.getDateOfBirth())){   
  52.                 java.text.DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");   
  53.                 rowi.createCell(3).setCellValue(format1.format(employeeInfo.getDateOfBirth()));   
  54.             }   
  55.             rowi.createCell(4).setCellValue(employeeInfo.getNationalIdentifier());   
  56.         }   
  57.         //写入数据  把相应的Excel 工作簿存盘   
  58.         book.write(os);   
  59.     } catch (IOException e) {   
  60.         e.printStackTrace();   
  61.     }   
  62. }  
[java] view plaincopyprint?
  1. /** 
  2.  * POI : 导出数据,存放于Excel中 
  3.  * @param os 输出流 (action: OutputStream os = response.getOutputStream();) 
  4.  * @param employeeInfos 要导出的数据集合 
  5.  */  
  6. public static void exportEmployeeByPoi(OutputStream os, List<EmployeeInfo> employeeInfos) {  
  7.       
  8.     try {  
  9.         //创建Excel工作薄   
  10.         HSSFWorkbook book = new HSSFWorkbook();  
  11.         //在Excel工作薄中建一张工作表   
  12.         HSSFSheet sheet = book.createSheet("员工信息");  
  13.         //设置单元格格式(文本)   
  14.         //HSSFCellStyle cellStyle = book.createCellStyle();   
  15.         //第一行为标题行   
  16.         HSSFRow row = sheet.createRow(0);//创建第一行   
  17.         HSSFCell cell0 = row.createCell(0);  
  18.         HSSFCell cell1 = row.createCell(1);  
  19.         HSSFCell cell2 = row.createCell(2);  
  20.         HSSFCell cell3 = row.createCell(3);  
  21.         HSSFCell cell4 = row.createCell(4);  
  22.         //定义单元格为字符串类型   
  23.         cell0.setCellType(HSSFCell.CELL_TYPE_STRING);  
  24.         cell1.setCellType(HSSFCell.CELL_TYPE_STRING);  
  25.         cell2.setCellType(HSSFCell.CELL_TYPE_STRING);  
  26.         cell3.setCellType(HSSFCell.CELL_TYPE_STRING);  
  27.         cell4.setCellType(HSSFCell.CELL_TYPE_STRING);  
  28.         //在单元格中输入数据   
  29.         cell0.setCellValue("员工编号");  
  30.         cell1.setCellValue("员工姓名");  
  31.         cell2.setCellValue("员工性别");  
  32.         cell3.setCellValue("出生日期");  
  33.         cell4.setCellValue("身份证号");  
  34.         //循环导出数据到excel中   
  35.         for(int i = 0; i < employeeInfos.size(); i++) {  
  36.             EmployeeInfo employeeInfo = employeeInfos.get(i);  
  37.             //创建第i行   
  38.             HSSFRow rowi = sheet.createRow(i + 1);  
  39.             //在第i行的相应列中加入相应的数据   
  40.             rowi.createCell(0).setCellValue(employeeInfo.getEmployeeNumber());  
  41.             rowi.createCell(1).setCellValue(employeeInfo.getFullName());  
  42.             //处理性别(M:男 F:女)   
  43.             String sex = null;  
  44.             if("M".equals(employeeInfo.getSex())) {  
  45.                 sex = "男";  
  46.             }else {  
  47.                 sex = "女";  
  48.             }  
  49.             rowi.createCell(2).setCellValue(sex);  
  50.             //对日期的处理   
  51.             if(employeeInfo.getDateOfBirth() != null && !"".equals(employeeInfo.getDateOfBirth())){  
  52.                 java.text.DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");  
  53.                 rowi.createCell(3).setCellValue(format1.format(employeeInfo.getDateOfBirth()));  
  54.             }  
  55.             rowi.createCell(4).setCellValue(employeeInfo.getNationalIdentifier());  
  56.         }  
  57.         //写入数据  把相应的Excel 工作簿存盘   
  58.         book.write(os);  
  59.     } catch (IOException e) {  
  60.         e.printStackTrace();  
  61.     }  
  62. }  
[java] view plaincopyprint?
  1. <span style="font-size:14px;"/** 
  2.      * POI : 导出数据,存放于Excel中 
  3.      * @param os 输出流 (action: OutputStream os = response.getOutputStream();) 
  4.      * @param employeeInfos 要导出的数据集合 
  5.      */  
  6.     public static void exportEmployeeByPoi(OutputStream os, List<EmployeeInfo> employeeInfos) {  
  7.           
  8.         try {  
  9.             //创建Excel工作薄  
  10.             HSSFWorkbook book = new HSSFWorkbook();  
  11.             //在Excel工作薄中建一张工作表  
  12.             HSSFSheet sheet = book.createSheet("员工信息");  
  13.             //设置单元格格式(文本)  
  14.             //HSSFCellStyle cellStyle = book.createCellStyle();  
  15.             //第一行为标题行  
  16.             HSSFRow row = sheet.createRow(0);//创建第一行  
  17.             HSSFCell cell0 = row.createCell(0);  
  18.             HSSFCell cell1 = row.createCell(1);  
  19.             HSSFCell cell2 = row.createCell(2);  
  20.             HSSFCell cell3 = row.createCell(3);  
  21.             HSSFCell cell4 = row.createCell(4);  
  22.             //定义单元格为字符串类型  
  23.             cell0.setCellType(HSSFCell.CELL_TYPE_STRING);  
  24.             cell1.setCellType(HSSFCell.CELL_TYPE_STRING);  
  25.             cell2.setCellType(HSSFCell.CELL_TYPE_STRING);  
  26.             cell3.setCellType(HSSFCell.CELL_TYPE_STRING);  
  27.             cell4.setCellType(HSSFCell.CELL_TYPE_STRING);  
  28.             //在单元格中输入数据  
  29.             cell0.setCellValue("员工编号");  
  30.             cell1.setCellValue("员工姓名");  
  31.             cell2.setCellValue("员工性别");  
  32.             cell3.setCellValue("出生日期");  
  33.             cell4.setCellValue("身份证号");  
  34.             //循环导出数据到excel中  
  35.             for(int i = 0; i < employeeInfos.size(); i++) {  
  36.                 EmployeeInfo employeeInfo = employeeInfos.get(i);  
  37.                 //创建第i行  
  38.                 HSSFRow rowi = sheet.createRow(i + 1);  
  39.                 //在第i行的相应列中加入相应的数据  
  40.                 rowi.createCell(0).setCellValue(employeeInfo.getEmployeeNumber());  
  41.                 rowi.createCell(1).setCellValue(employeeInfo.getFullName());  
  42.                 //处理性别(M:男 F:女)  
  43.                 String sex = null;  
  44.                 if("M".equals(employeeInfo.getSex())) {  
  45.                     sex = "男";  
  46.                 }else {  
  47.                     sex = "女";  
  48.                 }  
  49.                 rowi.createCell(2).setCellValue(sex);  
  50.                 //对日期的处理  
  51.                 if(employeeInfo.getDateOfBirth() != null && !"".equals(employeeInfo.getDateOfBirth())){  
  52.                     java.text.DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");  
  53.                     rowi.createCell(3).setCellValue(format1.format(employeeInfo.getDateOfBirth()));  
  54.                 }  
  55.                 rowi.createCell(4).setCellValue(employeeInfo.getNationalIdentifier());  
  56.             }  
  57.             //写入数据  把相应的Excel 工作簿存盘  
  58.             book.write(os);  
  59.         } catch (IOException e) {  
  60.             e.printStackTrace();  
  61.         }  
  62.     }</span>  

 action代码和导入的相似这里就不再进行赘述。

0 0