poi操作excel

转自:http://blog.csdn.net/chen_zw/article/details/8316028

poi是apache的子项目,专门用于处理Microsoft文档,其中HSSF和XSSF专门用于操作Excel表格(HSSF操作的是后缀名为.xls的文档(Excel 2003 以上),XSSF操作的是后缀名为.xlsx的文档(Excel 2007))。


所需jar包:poi-3.9-20121203.jar (当前最新jar包) 


Tag1:create Excel

[java]  view plain copy print ?
  1. /** 
  2.  * 创建Excle并写入数据 
  3.  * @author Ye 
  4.  * 
  5.  */  
  6. public class CreateExcel {  
  7.       
  8.      //测试数据,用于写入到Excel  
  9.      private static List<Student> getStudent() throws Exception{           
  10.              List<Student> list = new ArrayList<Student>();          
  11.              SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");         
  12.              Student user1 = new Student(1,"张三","男",16,df.parse("1997-03-12"));           
  13.              Student user2 = new Student(2,"李四","男",17,df.parse("1999-08-12"));           
  14.              Student user3 = new Student(3,"王五","女",26,df.parse("1985-11-12"));           
  15.              list.add(user1);           
  16.              list.add(user2);           
  17.              list.add(user3);                     
  18.              return list;       
  19.          }       
  20.       
  21.       
  22.      public static void main(String[] args) throws Exception {  
  23.            //第一步,创建一个webbook,对应一个Excel文件           
  24.                HSSFWorkbook wb = new HSSFWorkbook();    
  25.   
  26.               //第二步,在webbook中添加一个sheet,对应Excel文件中的sheet           
  27.               HSSFSheet studentSheet = wb.createSheet("学生信息");  
  28.     
  29.               //第三步,在sheet中添加表头行(即第0行),注意老版本poi对Excel的行数列数限制为short类型  
  30.               HSSFRow studentHeadRow = studentSheet.createRow(0);   
  31.           
  32.               //第四步,创建表头单元格,并设置单元格值居中(方法一:手动设置)  
  33.               HSSFCellStyle style = wb.createCellStyle();   //创建单元格样式        
  34.               style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置样式为居中显示             
  35.           
  36.               HSSFCell studentHeadcell = null;  
  37.               studentHeadcell = studentHeadRow.createCell(0);         
  38.               studentHeadcell.setCellValue("学号");   
  39.               studentHeadcell.setCellStyle(style);           
  40.               studentHeadcell = studentHeadRow.createCell(1);           
  41.               studentHeadcell.setCellValue("姓名");   
  42.               studentHeadcell.setCellStyle(style);           
  43.               studentHeadcell = studentHeadRow.createCell(2);           
  44.               studentHeadcell.setCellValue("性别");   
  45.               studentHeadcell.setCellStyle(style);           
  46.               studentHeadcell = studentHeadRow.createCell(3);           
  47.               studentHeadcell.setCellValue("年龄");   
  48.               studentHeadcell.setCellStyle(style);     
  49.               studentHeadcell = studentHeadRow.createCell(4);           
  50.               studentHeadcell.setCellValue("出生年月");   
  51.               studentHeadcell.setCellStyle(style);     
  52.           
  53.           
  54.              //方法二:通过反射机制获取类中的所有属性并设为表头  
  55. //           try {  
  56. //               Class<?> studentClass = Class.forName("Student");  //com.geocompass.model.STSTBPRPModel  
  57. //               Field[] fieldList = studentClass.getDeclaredFields();  
  58. //               for (int i = 0; i < fieldList.length; i++) {  
  59. //                    Field fld = fieldList[i];  
  60. //                    studentHeadRow.createCell(i).setCellValue(fld.getName());    
  61. //               }  
  62. //            } catch (ClassNotFoundException e) {  
  63. //               e.printStackTrace();  
  64. //            }  
  65.           
  66.               //第五步,写入实体数据  
  67.               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");  
  68.               List<Student> stuList = CreateExcel.getStudent();  //获取实体数据集  
  69.               HSSFRow studentRow = null;  //数据行  
  70.               for(int i=0;i<stuList.size();i++){               
  71.                studentRow = studentSheet.createRow(i+1);   
  72.                Student stu = (Student) stuList.get(i);               
  73.                studentRow.createCell(0).setCellValue(stu.getId());              
  74.                studentRow.createCell(1).setCellValue(stu.getName());              
  75.                studentRow.createCell(2).setCellValue(stu.getGender());              
  76.                studentRow.createCell(3).setCellValue(stu.getAge());    
  77.                studentRow.createCell(4).setCellValue(sdf.format(stu.getBirth()));  
  78.               }     
  79.           
  80.               //第六步,将文件存到指定位置           
  81.               try {             
  82.                FileOutputStream fout = new FileOutputStream("D:/student.xls");            
  83.                wb.write(fout);              
  84.                fout.close();      
  85.               } catch (Exception e) {             
  86.                e.printStackTrace();          
  87.               }    
  88.   
  89.              //或弹出下载对话框  
  90.              response.setContentType("application/ms-excel");  
  91.              response.setHeader("Content-Disposition" ,"attachment;filename="+new String("导出Excel.xls".getBytes(),"utf-8")) ;  
  92.              wb.write(response.getOutputStream());  
  93.        }  
  94. }  


Tag2:read from Excel

[java]  view plain copy print ?
  1. /** 
  2.  * 读取Excel 
  3.  * @author Ye 
  4.  * 
  5.  */  
  6. public class ReadExcel {  
  7.       
  8.     public static void main(String[] args) throws IOException, ParseException {  
  9.         //第一步:初始化Workbook对象。  
  10.         HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("D:/student.xls"));   
  11.         List<Student> stuList = new ArrayList<Student>();  
  12.           
  13.         //第二步:循环遍历获取Excel的sheet  
  14.         for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {   
  15.             HSSFSheet hssfSheet = wb.getSheetAt(sheetNum);   
  16.             if (hssfSheet == null) {   
  17.                 continue;   
  18.             }   
  19.               
  20.             Student stu = null;  
  21.             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");   
  22.   
  23.             //第三步:循环遍历获取第sheetNum个sheet的所有行记录  
  24.             for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {   
  25.                 HSSFRow hssfRow = hssfSheet.getRow(rowNum);   
  26.                 if (hssfRow == null) {   
  27.                     continue;   
  28.                 }   
  29.                   
  30.                 stu = new Student();   
  31.                   
  32.                 //第四步:获取每个单元格的值并赋值给stu对象  
  33.                 HSSFCell sid = hssfRow.getCell(0);  
  34.                 stu.setId(Integer.parseInt(getValue(sid)));  
  35.                   
  36.                 HSSFCell sname = hssfRow.getCell(1);   
  37.                 stu.setName(getValue(sname));  
  38.                   
  39.                 HSSFCell gender = hssfRow.getCell(2);   
  40.                 stu.setGender(getValue(gender));  
  41.                   
  42.                 HSSFCell age = hssfRow.getCell(3);   
  43.                 stu.setAge(Float.parseFloat(getValue(age)));  
  44.                   
  45.                 HSSFCell birth = hssfRow.getCell(4);   
  46.                 stu.setBirth(sdf.parse(getValue(birth)));  
  47.   
  48.                 stuList.add(stu);   
  49.             }   
  50.         }   
  51.   
  52.        //测试  
  53.        for(Student s:stuList)  
  54.        {  
  55.            System.out.println(s.getId() + "  " + s.getName() +"   " + s.getGender() + "   "+ s.getAge() + "   " + s.getBirth());  
  56.        }  
  57.           
  58.     }  
  59.       
  60.     //将Excel单元格中的数据都转化成String类型  
  61.     private static String getValue(HSSFCell hssfCell) {   
  62.         if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {   
  63.             return String.valueOf(hssfCell.getBooleanCellValue());  // 返回布尔类型的值   
  64.         } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {   
  65.             return String.valueOf(hssfCell.getNumericCellValue()); // 返回数值类型的值   
  66.         } else {   
  67.             return String.valueOf(hssfCell.getStringCellValue());  // 返回字符串类型的值   
  68.         }   
  69.     }   
  70.   
  71. }  

Notice:(1) 之前我一直使用Tomcat服务器运行代码,也没出过错,最近换成用Weblogic服务器,运行该代码时却报错:

java.lang.NoClassDefFoundError: org/apache/poi/hssf/usermodel/HSSFWorkbook

java.lang.ClassNotFoundException: org.apache.poi.hssf.usermodel.HSSFWorkbook

但明明都把poi-3.9-20121203.jar都已放到lib目录下,程序也都是自动部署的,为什么会找不到该jar包中的类呢?赶紧到weblogic服务器的部署目录(D:\Tool\bea\user_projects\domains\base_domain\servers\AdminServer\tmp\_WL_user\CMDB\i3s8gk\war\WEB-INF\lib)去看,果然没给我自动编译加载过来,重启下服务器,问题解决


/**
* 获取合并单元格的值

* @param sheet
* @param row
* @param column
* @return
*/
public static String getMergedRegionValue(Sheet sheet, int row, int column) {
sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell);
}
}
}
return null;
}
/**
* 判断指定的单元格是否是合并单元格

* @param sheet
* @param row
* @param column
* @return
*/
public static boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();// 得到所有区域/
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
sub = 0;
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
sub = lastRow - firstRow;
return true;
}
}
}
return false;
}
/**
* 获取单元格的值

* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
if (cell == null)
return "";
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return String.valueOf((int) cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf((int) cell.getNumericCellValue());
}
return "";
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值