用Apache POI来实现对Excel的读写

6 篇文章 0 订阅

转载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代码 复制代码
  1. import java.io.FileNotFoundException;   
  2. import java.io.FileOutputStream;   
  3. import java.io.IOException;   
  4.   
  5. import org.apache.poi.ss.usermodel.CreationHelper;   
  6. import org.apache.poi.ss.usermodel.Row;   
  7. import org.apache.poi.ss.usermodel.Sheet;   
  8. import org.apache.poi.ss.usermodel.Workbook;   
  9. import org.apache.poi.xssf.usermodel.XSSFWorkbook;   
  10. /**  
  11.  * 写入数据到Excel  
  12.  * @author http://www.lookhan.com  
  13.  *  
  14.  */  
  15. public class WriteExcel{   
  16.         
  17.       public static void main(String[] args){   
  18.           try{   
  19.               Workbook wb = new XSSFWorkbook();   
  20.               CreationHelper createHelper = wb.getCreationHelper();   
  21.               //创建页   
  22.               Sheet sheet = wb.createSheet("sheet1");   
  23.               // 创建行   
  24.               Row row = sheet.createRow((short0);   
  25.               // 创建单元格   
  26.               row.createCell(0).setCellValue(258258258);   
  27.               row.createCell(1).setCellValue(0.67);   
  28.               row.createCell(2).setCellValue(createHelper.createRichTextString("http://www.lookhan.com"));   
  29.               row.createCell(3).setCellValue(createHelper.createRichTextString("Java知识笔记"));   
  30.               // 写入文件   
  31.               FileOutputStream fileOut = null;   
  32.               fileOut = new FileOutputStream("D:\\lookhan.xlsx");   
  33.               wb.write(fileOut);   
  34.               fileOut.close();   
  35.               System.out.println("写入成功!");   
  36.           } catch (FileNotFoundException e){   
  37.               e.printStackTrace();   
  38.           } catch (IOException e){   
  39.               e.printStackTrace();   
  40.           }   
  41.       }   
  42.          
  43. }   

上面的测试类运行后,你就能在D盘下看到Excel文件了。

再看看如何读取Excel,首先定义一个自定义异常类,便于提示在读取Excel文件时出错的地方,因为一般对Excel的读取情况常见的是导入Excel数据到数据库中,一般如果用户在导入出错的话,可能是某个单元格的格式不对,用一个自定义异常可以很好的提示:

Java代码 复制代码
  1. /**  
  2.  * 读取Excel时格式错误的自定义Exception  
  3.  * @author http://www.lookhan.com  
  4.  *  
  5.  */  
  6. public class ExcelFormatException extends Exception {   
  7.   
  8.     private static final long serialVersionUID = 3435456589196458401L;   
  9.     private int row;   
  10.     private int column;   
  11.        
  12.     public ExcelFormatException(String message, int row, int column){   
  13.         super(message);   
  14.         this.row = row;   
  15.         this.column = column;   
  16.     }   
  17.     //出错的行   
  18.     public int getRow() {   
  19.         return row;   
  20.     }   
  21.     //出错的列   
  22.     public int getColumn() {   
  23.         return column;   
  24.     }   
  25.        
  26. }  

再来看看测试类:

Java代码 复制代码
  1. import java.io.FileInputStream;   
  2. import java.io.InputStream;   
  3.   
  4. import org.apache.poi.ss.usermodel.Cell;   
  5. import org.apache.poi.ss.usermodel.DateUtil;   
  6. import org.apache.poi.ss.usermodel.Row;   
  7. import org.apache.poi.ss.usermodel.Sheet;   
  8. import org.apache.poi.ss.usermodel.Workbook;   
  9. import org.apache.poi.ss.usermodel.WorkbookFactory;   
  10. /**  
  11.  * 测试对Excel的读取  
  12.  * @author http://www.lookhan.com  
  13.  *  
  14.  */  
  15. public class ReaderExcel {   
  16.   
  17.     public static void main(String[] args){   
  18.         String src = "D:\\lookhan.xlsx";   
  19.         try {   
  20.             ReaderExcel test = new ReaderExcel();   
  21.             test.getExcel(src);   
  22.         } catch (Exception e) {   
  23.             ExcelFormatException excelException = (ExcelFormatException)e;   
  24.             System.out.println(excelException.getMessage()+"行:"+excelException.getColumn()+"列:"+excelException.getRow());   
  25.         }   
  26.     }   
  27.   
  28.     public void getExcel(String src) throws Exception{   
  29.            
  30.         InputStream inp;   
  31.         inp = new FileInputStream(src);   
  32.         Workbook wb = WorkbookFactory.create(inp);   
  33.         //读取第一页   
  34.         Sheet sheet = wb.getSheetAt(0);   
  35.         //从第二行开始到最后一行(第一行是标题)   
  36.         for(int i=1; i1;i++){   
  37.             Row row = sheet.getRow(i);   
  38.             //循环四列(Excel是四列)   
  39.             for (int j=0; j<4; j++){   
  40.                 Cell cell = row.getCell(j);   
  41.                 if(j == 0){   
  42.                     switch (cell.getCellType()){   
  43.                         case Cell.CELL_TYPE_NUMERIC:   
  44.                             if (DateUtil.isCellDateFormatted(cell)){   
  45.                                 System.out.println(cell.getDateCellValue());   
  46.                             } else {   
  47.                                 throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  48.                             }   
  49.                             break;   
  50.                         default:   
  51.                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  52.                     }   
  53.                 }   
  54.                 if(j == 1){   
  55.                     switch (cell.getCellType()){   
  56.                         case Cell.CELL_TYPE_STRING:   
  57.                             System.out.println(cell.getRichStringCellValue());   
  58.                             break;   
  59.                         case Cell.CELL_TYPE_NUMERIC:   
  60.                             if (DateUtil.isCellDateFormatted(cell)){   
  61.                                 System.out.println(cell.getDateCellValue().toString());   
  62.                             } else {   
  63.                                 System.out.println(cell.getNumericCellValue());   
  64.                             }   
  65.                             break;   
  66.                         case Cell.CELL_TYPE_BOOLEAN:   
  67.                             System.out.println(cell.getBooleanCellValue());   
  68.                             break;   
  69.                         case Cell.CELL_TYPE_FORMULA:   
  70.                             System.out.println(cell.getCellFormula());   
  71.                             break;   
  72.                         default:   
  73.                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  74.                     }   
  75.                 }   
  76.                 if(j == 2){   
  77.                     switch (cell.getCellType()){   
  78.                         case Cell.CELL_TYPE_STRING:   
  79.                             System.out.println(cell.getRichStringCellValue());   
  80.                             break;   
  81.                         case Cell.CELL_TYPE_NUMERIC:   
  82.                             if (DateUtil.isCellDateFormatted(cell)){   
  83.                                 System.out.println(cell.getDateCellValue());   
  84.                             } else {   
  85.                                 System.out.println(cell.getNumericCellValue());   
  86.                             }   
  87.                             break;   
  88.                         case Cell.CELL_TYPE_BOOLEAN:   
  89.                             System.out.println(cell.getBooleanCellValue());   
  90.                             break;   
  91.                         case Cell.CELL_TYPE_FORMULA:   
  92.                             System.out.println(cell.getCellFormula());   
  93.                             break;   
  94.                         default:   
  95.                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  96.                     }   
  97.                 }   
  98.                 if(j == 3){   
  99.                     switch (cell.getCellType()){   
  100.                         case Cell.CELL_TYPE_STRING:   
  101.                             System.out.println(cell.getRichStringCellValue());   
  102.                             break;   
  103.                         case Cell.CELL_TYPE_NUMERIC:   
  104.                             if (DateUtil.isCellDateFormatted(cell)){   
  105.                                 throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  106.                             } else {   
  107.                                 System.out.println(cell.getNumericCellValue());   
  108.                             }   
  109.                             break;   
  110.                         case Cell.CELL_TYPE_BOOLEAN:   
  111.                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  112.                         case Cell.CELL_TYPE_FORMULA:   
  113.                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  114.                         default:   
  115.                             throw new ExcelFormatException("格式错误",(cell.getRowIndex()+1),(cell.getColumnIndex()+1));   
  116.                     }   
  117.                 }   
  118.             }   
  119.         }   
  120.         inp.close();   
  121.            
  122.     }   
  123.        
  124. }  

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值