如何创建和读取excel文件-poi的简单使用

原文转载:http://blog.csdn.net/sidongxue2/article/details/38423135

Jakarta POI是apache的子项目,它提供了一组操纵Windows文档的Java API,通过它可以用纯Java代码来读取,写入和修改Excel文件.
本实例将excel内容抽象为一个Map<String, Map<String, List<String>>>,第一个key为sheet的名称,第二个key为行号.

1.实现将map写入excel,直接看代码ExcelExprotUtil.

[java]  view plain  copy
  1. package com.ilucky.poi.util;  
  2.   
  3. import java.io.BufferedOutputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7. import java.util.Map.Entry;  
  8.   
  9. import org.apache.poi.hssf.usermodel.HSSFCell;  
  10. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  11. import org.apache.poi.hssf.usermodel.HSSFRow;  
  12. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  14.   
  15. /** 
  16.  * @author IluckySi 
  17.  * @date 20140807 
  18.  */  
  19. public class ExcelExportUtil {  
  20.   
  21.     private String path;  
  22.       
  23.     private String name;  
  24.       
  25.     private Map<String, Map<String, List<String>>> excel;  
  26.       
  27.     public ExcelExportUtil(Map<String, Map<String, List<String>>> excel) {  
  28.         this.excel = excel;  
  29.     }  
  30.       
  31.     public String getPath() {  
  32.         return path;  
  33.     }  
  34.   
  35.     public void setPath(String path) {  
  36.         this.path = path;  
  37.     }  
  38.   
  39.     public String getName() {  
  40.         return name;  
  41.     }  
  42.   
  43.     public void setName(String name) {  
  44.         this.name = name;  
  45.     }  
  46.   
  47.     public void exportExcel() {  
  48.         FileOutputStream fos = null;  
  49.         BufferedOutputStream bos = null;  
  50.         try {  
  51.             //校验数据源是否合法.  
  52.             if(excel.size() <= 0) {  
  53.                 try {  
  54.                     throw new Exception("excel数据源有问题!");  
  55.                 } catch (Exception e) {  
  56.                     e.printStackTrace();  
  57.                 }  
  58.             }  
  59.               
  60.             //创建excel.  
  61.             HSSFWorkbook hssfWorkbook = new HSSFWorkbook();  
  62.             int sheetCount = 0;  
  63.             for(Entry<String, Map<String, List<String>>> sheet : excel.entrySet()) {  
  64.                 //创建sheet并命名.  
  65.                 String sheetName = sheet.getKey();  
  66.                 HSSFSheet hssfSheet = hssfWorkbook.createSheet();  
  67.                 hssfWorkbook.setSheetName(sheetCount, sheetName);  
  68.                 Map<String, List<String>> sheetValue = sheet.getValue();  
  69.                 for(Entry<String, List<String>> row : sheetValue.entrySet()) {  
  70.                     //创建行.  
  71.                     int rowNumber = Integer.parseInt(row.getKey());  
  72.                      HSSFRow hssfRow = hssfSheet.createRow(rowNumber);    
  73.                      List<String> rowValue = row.getValue();  
  74.                      for(int i = 0; rowValue != null && i < rowValue.size(); i++) {  
  75.                          //创建单元格并写入内容.  
  76.                         String cellValue = rowValue.get(i);  
  77.                         HSSFCell hssfCell = hssfRow.createCell((short)i);    
  78.                         hssfCell.setCellValue(new HSSFRichTextString(cellValue));    
  79.                      }  
  80.                 }  
  81.                 sheetCount++;  
  82.             }  
  83.               
  84.             //导出为excel.  
  85.             fos = new FileOutputStream(path + "/" + name);  
  86.             bos = new BufferedOutputStream(fos);    
  87.             hssfWorkbook.write(bos);    
  88.         } catch (Exception e) {  
  89.             System.out.println("导出excel发生问题: " + e);  
  90.         } finally {  
  91.             try {  
  92.                 if(bos != null) {  
  93.                     bos.close();  
  94.                     bos = null;  
  95.                 }  
  96.                 if(fos != null) {  
  97.                     fos.close();  
  98.                     fos = null;  
  99.                 }  
  100.             } catch (Exception e) {  
  101.                 System.out.println("关闭文件流发生问题: " + e);  
  102.             }  
  103.         }  
  104.     }  
  105. }  

2.实现将excel中的内容放入map,直接看代码ExcelImportUtil.

[java]  view plain  copy
  1. package com.ilucky.poi.util;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.Iterator;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import org.apache.poi.hssf.usermodel.HSSFCell;  
  11. import org.apache.poi.hssf.usermodel.HSSFRow;  
  12. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  14. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
  15.   
  16. /** 
  17.  * @author IluckySi 
  18.  * @date 20140807 
  19.  */  
  20. public class ExcelImportUtil {  
  21.   
  22.     private String path;  
  23.       
  24.     private String name;  
  25.       
  26.     private Map<String, Map<String, List<String>>> excel;  
  27.       
  28.     public ExcelImportUtil() {  
  29.          excel = new HashMap<String, Map<String, List<String>>>();  
  30.     }  
  31.       
  32.     public String getPath() {  
  33.         return path;  
  34.     }  
  35.   
  36.     public void setPath(String path) {  
  37.         this.path = path;  
  38.     }  
  39.   
  40.     public String getName() {  
  41.         return name;  
  42.     }  
  43.   
  44.     public void setName(String name) {  
  45.         this.name = name;  
  46.     }  
  47.   
  48.     public Map<String, Map<String, List<String>>> importExcel () {  
  49.         //创建一个map存放excel中的数据.  
  50.         FileInputStream fis = null;  
  51.         try {  
  52.             //加载要读取的excel文件.  
  53.             fis = new FileInputStream(path + "/" + name);  
  54.             POIFSFileSystem pfs = new POIFSFileSystem(fis);  
  55.             HSSFWorkbook hssfWorkbook = new HSSFWorkbook(pfs);  
  56.             int sheetCount = getSheetCount(hssfWorkbook);  
  57.             for(int i = 0; i < sheetCount; i++) {  
  58.                 //获取sheet.  
  59.                 Map<String, List<String>> sheet = new HashMap<String, List<String>>();  
  60.                 String sheetName = hssfWorkbook.getSheetName(i);  
  61.                 HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i);  
  62.                 @SuppressWarnings("unchecked")  
  63.                 Iterator<HSSFRow>rowIteraotr = hssfSheet.rowIterator();  
  64.                 //获取行.  
  65.                 int rowNumber = 0;  
  66.                 while(rowIteraotr.hasNext()) {  
  67.                     List<String> rowList = new ArrayList<String>();  
  68.                      HSSFRow hssfRow = rowIteraotr.next();  
  69.                      @SuppressWarnings("unchecked")  
  70.                     Iterator<HSSFCell> cellIterator = hssfRow.cellIterator();  
  71.                      while(cellIterator.hasNext()) {  
  72.                         //获取单元格内数据.  
  73.                          HSSFCell hssfCell = cellIterator.next();  
  74.                          String cellValue =hssfCell.getRichStringCellValue().toString();  
  75.                          rowList.add(cellValue);  
  76.                      }  
  77.                      sheet.put(rowNumber + "", rowList);  
  78.                      rowNumber++;  
  79.                 }  
  80.                 excel.put(sheetName, sheet);  
  81.             }  
  82.         } catch (Exception e) {  
  83.             System.out.println("获取excel数据发生问题: " + e);  
  84.         } finally {  
  85.             try {  
  86.                 if(fis != null) {  
  87.                     fis.close();  
  88.                     fis = null;  
  89.                 }  
  90.             } catch (Exception e) {  
  91.                 System.out.println("关闭文件流发生问题: " + e);  
  92.             }  
  93.         }  
  94.         return excel;  
  95.     }  
  96.       
  97.     @SuppressWarnings("unused")  
  98.     public static int getSheetCount(HSSFWorkbook hssfWorkbook) {  
  99.         int count = 0;  
  100.         try {  
  101.             for(int i = 0; i < 255; i++) {  
  102.                 count = i;  
  103.                  HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i);  
  104.             }  
  105.         } catch (Exception e) {  
  106.             return count;  
  107.         } finally {  
  108.             System.out.println("此excel共有" + count + "个sheet!");  
  109.         }  
  110.         return count;  
  111.     }  
  112. }  

3.最后看测试类MainTest.

[java]  view plain  copy
  1. package com.ilucky.poi;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7. import java.util.Map.Entry;  
  8.   
  9. import com.ilucky.poi.util.ExcelExportUtil;  
  10. import com.ilucky.poi.util.ExcelImportUtil;  
  11.   
  12. /** 
  13.  * @author IluckySi 
  14.  * @date 20140807 
  15.  */  
  16. public class MainTest {  
  17.         
  18.     public static void main(String[] args) {    
  19.           
  20.         //写入excel数据.  
  21.         exportExcel();  
  22.           
  23.         //读取excel数据.  
  24.         importExcel();  
  25.     }  
  26.       
  27.     public static void exportExcel() {  
  28.         //创建一个map模拟excel中的数据.  
  29.         Map<String, Map<String, List<String>>> excel = new HashMap<String, Map<String, List<String>>>();  
  30.           
  31.         //创建一个map模拟第一个sheet中的数据.  
  32.         Map<String, List<String>> sheet1 = new HashMap<String, List<String>>();  
  33.         //创建一个list模拟第一行的数据.  
  34.         List<String> sheet1_row1 = new ArrayList<String>();  
  35.         sheet1_row1.add("姓名");  
  36.         sheet1_row1.add("年龄");  
  37.         sheet1_row1.add("学历");  
  38.         sheet1.put("0", sheet1_row1);  
  39.         //创建一个list模拟第二行的数据.  
  40.         List<String> sheet1_row2 = new ArrayList<String>();  
  41.         sheet1_row2.add("司冬雪");  
  42.         sheet1_row2.add("26");  
  43.         sheet1_row2.add("大专");  
  44.         sheet1.put("1", sheet1_row2);  
  45.         //创建一个list模拟第三行的数据.  
  46.         List<String> sheet1_row3 = new ArrayList<String>();  
  47.         sheet1_row3.add("爱谁谁");  
  48.         sheet1_row3.add("26");  
  49.         sheet1_row3.add("本科");  
  50.         sheet1.put("2", sheet1_row3);  
  51.         excel.put("sheet_name1", sheet1);  
  52.           
  53.         //创建一个map模拟第一个sheet中的数据.  
  54.         Map<String, List<String>> sheet2 = new HashMap<String, List<String>>();  
  55.         //创建一个list模拟第一行的数据.  
  56.         List<String> sheet2_row1 = new ArrayList<String>();  
  57.         sheet2_row1.add("演员");  
  58.         sheet2_row1.add("职业");  
  59.         sheet2_row1.add("年龄");  
  60.         sheet2.put("0", sheet2_row1);  
  61.         //创建一个list模拟第二行的数据.  
  62.         List<String> sheet2_row2 = new ArrayList<String>();  
  63.         sheet2_row2.add("郭德纲");  
  64.         sheet2_row2.add("相声演员");  
  65.         sheet2_row2.add("40");  
  66.         sheet2.put("1", sheet2_row2);  
  67.         //创建一个list模拟第三行的数据.  
  68.         List<String> sheet2_row3 = new ArrayList<String>();  
  69.         sheet2_row3.add("赵本山");  
  70.         sheet2_row3.add("小品演员");  
  71.         sheet2_row3.add("55");  
  72.         sheet2.put("2", sheet2_row3);  
  73.         excel.put("sheet_name2", sheet2);  
  74.           
  75.         //将数据源写入excel.  
  76.         ExcelExportUtil eeu = new ExcelExportUtil(excel);  
  77.         eeu.setPath("D:/");  
  78.         eeu.setName("excel_exprot.xls");  
  79.         eeu.exportExcel();  
  80.     }    
  81.       
  82.     public static void importExcel() {  
  83.         //创建一个map存放excel中的数据.  
  84.         Map<String, Map<String, List<String>>> excel = new HashMap<String, Map<String, List<String>>>();  
  85.           
  86.         //读取excel数据.  
  87.         ExcelImportUtil eiu = new ExcelImportUtil();  
  88.         eiu.setPath("D:/");  
  89.         eiu.setName("excel_exprot.xls");  
  90.         excel = eiu.importExcel();  
  91.           
  92.         //遍历获取的excel数据.  
  93.         for(Entry<String, Map<String, List<String>>> map : excel.entrySet()) {  
  94.             String sheetKey = map.getKey();  
  95.             System.out.println("sheet_name: " + sheetKey);  
  96.             Map<String, List<String>> sheetValue = map.getValue();  
  97.             for(Entry<String, List<String>> row : sheetValue.entrySet()) {  
  98.                 String rowNumber = row.getKey();  
  99.                 System.out.println("第" + rowNumber + "行数据: ");  
  100.                 List<String> rowValue = row.getValue();  
  101.                 for(int i = 0; rowValue != null && i < rowValue.size(); i++) {  
  102.                     String cellValue = rowValue.get(i);  
  103.                     System.out.println("第" + i + "个单元格的数据: " + cellValue);  
  104.                 }  
  105.             }  
  106.         }  
  107.     }  
  108. }  
  109. /** 
  110. excel共有2个sheet! 
  111. sheet_name: sheet_name1 
  112. 第2行数据:  
  113. 第0个单元格的数据: 爱谁谁 
  114. 第1个单元格的数据: 26 
  115. 第2个单元格的数据: 本科 
  116. 第1行数据:  
  117. 第0个单元格的数据: 司冬雪 
  118. 第1个单元格的数据: 26 
  119. 第2个单元格的数据: 大专 
  120. 第0行数据:  
  121. 第0个单元格的数据: 姓名 
  122. 第1个单元格的数据: 年龄 
  123. 第2个单元格的数据: 学历 
  124. sheet_name: sheet_name2 
  125. 第2行数据:  
  126. 第0个单元格的数据: 赵本山 
  127. 第1个单元格的数据: 小品演员 
  128. 第2个单元格的数据: 55 
  129. 第1行数据:  
  130. 第0个单元格的数据: 郭德纲 
  131. 第1个单元格的数据: 相声演员 
  132. 第2个单元格的数据: 40 
  133. 第0行数据:  
  134. 第0个单元格的数据: 演员 
  135. 第1个单元格的数据: 职业 
  136. 第2个单元格的数据: 年龄 
  137. */  

原文转载:http://blog.csdn.net/sidongxue2/article/details/38423135

扫描二维码关注公众号,回复: 2223200 查看本文章

猜你喜欢

转载自blog.csdn.net/zz775854904/article/details/79653867