设为首页 收藏本站
查看: 428|回复: 0

[经验分享] 用Apache POI来实现对Excel的读写

[复制链接]

尚未签到

发表于 2017-1-9 09:27:44 | 显示全部楼层 |阅读模式
  转载http://www.lookhan.com/experience/experience/20110113211355.html
  在我们的项目当中经常会遇到把数据导入到Excel中,或者读取Excel中的数据到数据库中,用Apache POI可以很方便的实现,Apache POI是Apache基金会的开放源码函式库,可以在其官网上下载其Jar包,官网是http://poi.apache.org,下载后把里面所有的jar包拷贝到项目中(其中不仅仅是根目录下的Jar包),好,我们先来看看如何写入数据到Excel中,注意,这里讲的是针对Excel 2007的,如果是以前的版本的,读取的方式是不一样的,请注意:
Java代码复制代码

  • import java.io.FileNotFoundException;   
  • import java.io.FileOutputStream;   
  • import java.io.IOException;   
  •   
  • import org.apache.poi.ss.usermodel.CreationHelper;   
  • import org.apache.poi.ss.usermodel.Row;   
  • import org.apache.poi.ss.usermodel.Sheet;   
  • import org.apache.poi.ss.usermodel.Workbook;   
  • import org.apache.poi.xssf.usermodel.XSSFWorkbook;   
  • /**  
  •  * 写入数据到Excel  
  •  * @author http://www.lookhan.com  
  •  *  
  •  */  
  • public class WriteExcel{   
  •         
  •       public static void main(String[] args){   
  •           try{   
  •               Workbook wb = new XSSFWorkbook();   
  •               CreationHelper createHelper = wb.getCreationHelper();   
  •               //创建页   
  •               Sheet sheet = wb.createSheet("sheet1");   
  •               // 创建行   
  •               Row row = sheet.createRow((short0);   
  •               // 创建单元格   
  •               row.createCell(0).setCellValue(258258258);   
  •               row.createCell(1).setCellValue(0.67);   
  •               row.createCell(2).setCellValue(createHelper.createRichTextString("http://www.lookhan.com"));   
  •               row.createCell(3).setCellValue(createHelper.createRichTextString("Java知识笔记"));   
  •               // 写入文件   
  •               FileOutputStream fileOut = null;   
  •               fileOut = new FileOutputStream("D:\\lookhan.xlsx");   
  •               wb.write(fileOut);   
  •               fileOut.close();   
  •               System.out.println("写入成功!");   
  •           } catch (FileNotFoundException e){   
  •               e.printStackTrace();   
  •           } catch (IOException e){   
  •               e.printStackTrace();   
  •           }   
  •       }   
  •          
  • }   


  上面的测试类运行后,你就能在D盘下看到Excel文件了。
  再看看如何读取Excel,首先定义一个自定义异常类,便于提示在读取Excel文件时出错的地方,因为一般对Excel的读取情况常见的是导入Excel数据到数据库中,一般如果用户在导入出错的话,可能是某个单元格的格式不对,用一个自定义异常可以很好的提示:
Java代码复制代码

  • /**  
  •  * 读取Excel时格式错误的自定义Exception  
  •  * @author http://www.lookhan.com  
  •  *  
  •  */  
  • public class ExcelFormatException extends Exception {   
  •   
  •     private static final long serialVersionUID = 3435456589196458401L;   
  •     private int row;   
  •     private int column;   
  •        
  •     public ExcelFormatException(String message, int row, int column){   
  •         super(message);   
  •         this.row = row;   
  •         this.column = column;   
  •     }   
  •     //出错的行   
  •     public int getRow() {   
  •         return row;   
  •     }   
  •     //出错的列   
  •     public int getColumn() {   
  •         return column;   
  •     }   
  •        
  • }  


  再来看看测试类:
Java代码复制代码

  • import java.io.FileInputStream;   
  • import java.io.InputStream;   
  •   
  • import org.apache.poi.ss.usermodel.Cell;   
  • import org.apache.poi.ss.usermodel.DateUtil;   
  • import org.apache.poi.ss.usermodel.Row;   
  • import org.apache.poi.ss.usermodel.Sheet;   
  • import org.apache.poi.ss.usermodel.Workbook;   
  • import org.apache.poi.ss.usermodel.WorkbookFactory;   
  • /**  
  •  * 测试对Excel的读取  
  •  * @author http://www.lookhan.com  
  •  *  
  •  */  
  • public class ReaderExcel {   
  •   
  •     public static void main(String[] args){   
  •         String src = "D:\\lookhan.xlsx";   
  •         try {   
  •             ReaderExcel test = new ReaderExcel();   
  •             test.getExcel(src);   
  •         } catch (Exception e) {   
  •             ExcelFormatException excelException = (ExcelFormatException)e;   
  •             System.out.println(excelException.getMessage()+"行:"+excelException.getColumn()+"列:"+excelException.getRow());   
  •         }   
  •     }   
  •   
  •     public void getExcel(String src) throws Exception{   
  •            
  •         InputStream inp;   
  •         inp = new FileInputStream(src);   
  •         Workbook wb = WorkbookFactory.create(inp);   
  •         //读取第一页   
  •         Sheet sheet = wb.getSheetAt(0);   
  •         //从第二行开始到最后一行(第一行是标题)   
  •         for(int i=1; i1;i++){   
  •             Row row = sheet.getRow(i);   
  •             //循环四列(Excel是四列)   
  •             for (int j=0; j<4; j++){   
  •                 Cell cell = row.getCell(j);   
  •                 if(j == 0){   
  •                     switch (cell.getCellType()){   
  •                         case Cell.CELL_TYPE_NUMERIC:   
  •                             if (DateUtil.isCellDateFormatted(cell)){   
  •                                 System.out.println(cell.getDateCellValue());   
  •                             } else {   
  •                                 throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                             }   
  •                             break;   
  •                         default:   
  •                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                     }   
  •                 }   
  •                 if(j == 1){   
  •                     switch (cell.getCellType()){   
  •                         case Cell.CELL_TYPE_STRING:   
  •                             System.out.println(cell.getRichStringCellValue());   
  •                             break;   
  •                         case Cell.CELL_TYPE_NUMERIC:   
  •                             if (DateUtil.isCellDateFormatted(cell)){   
  •                                 System.out.println(cell.getDateCellValue().toString());   
  •                             } else {   
  •                                 System.out.println(cell.getNumericCellValue());   
  •                             }   
  •                             break;   
  •                         case Cell.CELL_TYPE_BOOLEAN:   
  •                             System.out.println(cell.getBooleanCellValue());   
  •                             break;   
  •                         case Cell.CELL_TYPE_FORMULA:   
  •                             System.out.println(cell.getCellFormula());   
  •                             break;   
  •                         default:   
  •                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                     }   
  •                 }   
  •                 if(j == 2){   
  •                     switch (cell.getCellType()){   
  •                         case Cell.CELL_TYPE_STRING:   
  •                             System.out.println(cell.getRichStringCellValue());   
  •                             break;   
  •                         case Cell.CELL_TYPE_NUMERIC:   
  •                             if (DateUtil.isCellDateFormatted(cell)){   
  •                                 System.out.println(cell.getDateCellValue());   
  •                             } else {   
  •                                 System.out.println(cell.getNumericCellValue());   
  •                             }   
  •                             break;   
  •                         case Cell.CELL_TYPE_BOOLEAN:   
  •                             System.out.println(cell.getBooleanCellValue());   
  •                             break;   
  •                         case Cell.CELL_TYPE_FORMULA:   
  •                             System.out.println(cell.getCellFormula());   
  •                             break;   
  •                         default:   
  •                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                     }   
  •                 }   
  •                 if(j == 3){   
  •                     switch (cell.getCellType()){   
  •                         case Cell.CELL_TYPE_STRING:   
  •                             System.out.println(cell.getRichStringCellValue());   
  •                             break;   
  •                         case Cell.CELL_TYPE_NUMERIC:   
  •                             if (DateUtil.isCellDateFormatted(cell)){   
  •                                 throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                             } else {   
  •                                 System.out.println(cell.getNumericCellValue());   
  •                             }   
  •                             break;   
  •                         case Cell.CELL_TYPE_BOOLEAN:   
  •                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                         case Cell.CELL_TYPE_FORMULA:   
  •                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                         default:   
  •                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  •                     }   
  •                 }   
  •             }   
  •         }   
  •         inp.close();   
  •            
  •     }   
  •        
  • }  


  上面的读取Excel的代码写的可能不是很好,里面有好多的判断,是这样的,POI对Excel的读取是要看里面数据的类型的,而有些数据有可能是字符串,又有可能是数字类型,而对不同的类型的读取所用的方法是不一样的,所以我在这里是先得到数据的类型,然后根据其类型来调用不同的方法。感觉这里用的不是很好,可是我也找不到比较好的方法,有知道的告诉我一声。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-325813-1-1.html 上篇帖子: How to compile Apache-2.2.11 to ARM 下篇帖子: Java日志学习二:Apache Commons Logging (JCL)源码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表