POI实现导入导出

  1. import java.util.Date;  
  2.   
  3. public class Student  
  4. {  
  5.     private int id;  
  6.     private String name;  
  7.     private int age;  
  8.     private Date birth;  
  9.   
  10.     public Student()  
  11.     {  
  12.     }  
  13.   
  14.     public Student(int id, String name, int age, Date birth)  
  15.     {  
  16.         this.id = id;  
  17.         this.name = name;  
  18.         this.age = age;  
  19.         this.birth = birth;  
  20.     }  
  21.   
  22.     public int getId()  
  23.     {  
  24.         return id;  
  25.     }  
  26.   
  27.     public void setId(int id)  
  28.     {  
  29.         this.id = id;  
  30.     }  
  31.   
  32.     public String getName()  
  33.     {  
  34.         return name;  
  35.     }  
  36.   
  37.     public void setName(String name)  
  38.     {  
  39.         this.name = name;  
  40.     }  
  41.   
  42.     public int getAge()  
  43.     {  
  44.         return age;  
  45.     }  
  46.   
  47.     public void setAge(int age)  
  48.     {  
  49.         this.age = age;  
  50.     }  
  51.   
  52.     public Date getBirth()  
  53.     {  
  54.         return birth;  
  55.     }  
  56.   
  57.     public void setBirth(Date birth)  
  58.     {  
  59.         this.birth = birth;  
  60.     }  
  61.   
  62. }  
3.CreateSimpleExcelToDisk.java

  1. import java.io.FileOutputStream;  
  2. import java.text.SimpleDateFormat;  
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.poi.hssf.usermodel.HSSFCell;  
  7. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  8. import org.apache.poi.hssf.usermodel.HSSFRow;  
  9. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  11.   
  12. public class CreateSimpleExcelToDisk  
  13. {  
  14.     /** 
  15.      * @功能:手工构建一个简单格式的Excel 
  16.      */  
  17.     private static List<Student> getStudent() throws Exception  
  18.     {  
  19.         List list = new ArrayList();  
  20.         SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");  
  21.   
  22.         Student user1 = new Student(1"张三"16, df.parse("1997-03-12"));  
  23.         Student user2 = new Student(2"李四"17, df.parse("1996-08-12"));  
  24.         Student user3 = new Student(3"王五"26, df.parse("1985-11-12"));  
  25.         list.add(user1);  
  26.         list.add(user2);  
  27.         list.add(user3);  
  28.   
  29.         return list;  
  30.     }  
  31.   
  32.     public static void main(String[] args) throws Exception  
  33.     {  
  34.         // 第一步,创建一个webbook,对应一个Excel文件  
  35.         HSSFWorkbook wb = new HSSFWorkbook();  
  36.         // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
  37.         HSSFSheet sheet = wb.createSheet("学生表一");  
  38.         // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
  39.         HSSFRow row = sheet.createRow((int0);  
  40.         // 第四步,创建单元格,并设置值表头 设置表头居中  
  41.         HSSFCellStyle style = wb.createCellStyle();  
  42.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
  43.   
  44.         HSSFCell cell = row.createCell((short0);  
  45.         cell.setCellValue("学号");  
  46.         cell.setCellStyle(style);  
  47.         cell = row.createCell((short1);  
  48.         cell.setCellValue("姓名");  
  49.         cell.setCellStyle(style);  
  50.         cell = row.createCell((short2);  
  51.         cell.setCellValue("年龄");  
  52.         cell.setCellStyle(style);  
  53.         cell = row.createCell((short3);  
  54.         cell.setCellValue("生日");  
  55.         cell.setCellStyle(style);  
  56.   
  57.         // 第五步,写入实体数据 实际应用中这些数据从数据库得到,  
  58.         List list = CreateSimpleExcelToDisk.getStudent();  
  59.   
  60.         for (int i = 0; i < list.size(); i++)  
  61.         {  
  62.             row = sheet.createRow((int) i + 1);  
  63.             Student stu = (Student) list.get(i);  
  64.             // 第四步,创建单元格,并设置值  
  65.             row.createCell((short0).setCellValue((double) stu.getId());  
  66.             row.createCell((short1).setCellValue(stu.getName());  
  67.             row.createCell((short2).setCellValue((double) stu.getAge());  
  68.             cell = row.createCell((short3);  
  69.             cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu  
  70.                     .getBirth()));  
  71.         }  
  72.         // 第六步,将文件存到指定位置  
  73.         try  
  74.         {  
  75.             FileOutputStream fout = new FileOutputStream("E:/students.xls");  
  76.             wb.write(fout);  
  77.             fout.close();  
  78.         }  
  79.         catch (Exception e)  
  80.         {  
  81.             e.printStackTrace();  
  82.         }  
  83.     }  

  1. }  
  2. ----------------------------------------------------------------------------------------
    1. /** 
    2.  * Jun 25, 2012 
    3.  */  
    4.   
    5. import java.io.File;  
    6. import java.io.FileInputStream;  
    7. import java.io.IOException;  
    8. import java.io.InputStream;  
    9. import java.util.ArrayList;  
    10. import java.util.List;  
    11.   
    12. import org.apache.commons.io.FilenameUtils;  
    13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
    14. import org.apache.poi.ss.usermodel.Cell;  
    15. import org.apache.poi.ss.usermodel.CellValue;  
    16. import org.apache.poi.ss.usermodel.FormulaEvaluator;  
    17. import org.apache.poi.ss.usermodel.Row;  
    18. import org.apache.poi.ss.usermodel.Sheet;  
    19. import org.apache.poi.ss.usermodel.Workbook;  
    20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
    21.   
    22. /** 
    23.  * Excel组件 
    24.  *  
    25.  * @author Snowolf 
    26.  * @version 1.0 
    27.  * @since 1.0 
    28.  */  
    29. public abstract class ExcelHelper {  
    30.   
    31.     /** 
    32.      * Excel 2003 
    33.      */  
    34.     private final static String XLS = "xls";  
    35.     /** 
    36.      * Excel 2007 
    37.      */  
    38.     private final static String XLSX = "xlsx";  
    39.     /** 
    40.      * 分隔符 
    41.      */  
    42.     private final static String SEPARATOR = "|";  
    43.   
    44.     /** 
    45.      * 由Excel文件的Sheet导出至List 
    46.      *  
    47.      * @param file 
    48.      * @param sheetNum 
    49.      * @return 
    50.      */  
    51.     public static List<String> exportListFromExcel(File file, int sheetNum)  
    52.             throws IOException {  
    53.         return exportListFromExcel(new FileInputStream(file),  
    54.                 FilenameUtils.getExtension(file.getName()), sheetNum);  
    55.     }  
    56.   
    57.     /** 
    58.      * 由Excel流的Sheet导出至List 
    59.      *  
    60.      * @param is 
    61.      * @param extensionName 
    62.      * @param sheetNum 
    63.      * @return 
    64.      * @throws IOException 
    65.      */  
    66.     public static List<String> exportListFromExcel(InputStream is,  
    67.             String extensionName, int sheetNum) throws IOException {  
    68.   
    69.         Workbook workbook = null;  
    70.   
    71.         if (extensionName.toLowerCase().equals(XLS)) {  
    72.             workbook = new HSSFWorkbook(is);  
    73.         } else if (extensionName.toLowerCase().equals(XLSX)) {  
    74.             workbook = new XSSFWorkbook(is);  
    75.         }  
    76.   
    77.         return exportListFromExcel(workbook, sheetNum);  
    78.     }  
    79.   
    80.     /** 
    81.      * 由指定的Sheet导出至List 
    82.      *  
    83.      * @param workbook 
    84.      * @param sheetNum 
    85.      * @return 
    86.      * @throws IOException 
    87.      */  
    88.     private static List<String> exportListFromExcel(Workbook workbook,  
    89.             int sheetNum) {  
    90.   
    91.         Sheet sheet = workbook.getSheetAt(sheetNum);  
    92.   
    93.         // 解析公式结果  
    94.         FormulaEvaluator evaluator = workbook.getCreationHelper()  
    95.                 .createFormulaEvaluator();  
    96.   
    97.         List<String> list = new ArrayList<String>();  
    98.   
    99.         int minRowIx = sheet.getFirstRowNum();  
    100.         int maxRowIx = sheet.getLastRowNum();  
    101.         for (int rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) {  
    102.             Row row = sheet.getRow(rowIx);  
    103.             StringBuilder sb = new StringBuilder();  
    104.   
    105.             short minColIx = row.getFirstCellNum();  
    106.             short maxColIx = row.getLastCellNum();  
    107.             for (short colIx = minColIx; colIx <= maxColIx; colIx++) {  
    108.                 Cell cell = row.getCell(new Integer(colIx));  
    109.                 CellValue cellValue = evaluator.evaluate(cell);  
    110.                 if (cellValue == null) {  
    111.                     continue;  
    112.                 }  
    113.                 // 经过公式解析,最后只存在Boolean、Numeric和String三种数据类型,此外就是Error了  
    114.                 // 其余数据类型,根据官方文档,完全可以忽略http://poi.apache.org/spreadsheet/eval.html  
    115.                 switch (cellValue.getCellType()) {  
    116.                 case Cell.CELL_TYPE_BOOLEAN:  
    117.                     sb.append(SEPARATOR + cellValue.getBooleanValue());  
    118.                     break;  
    119.                 case Cell.CELL_TYPE_NUMERIC:  
    120.                     // 这里的日期类型会被转换为数字类型,需要判别后区分处理  
    121.                     if (DateUtil.isCellDateFormatted(cell)) {  
    122.                         sb.append(SEPARATOR + cell.getDateCellValue());  
    123.                     } else {  
    124.                         sb.append(SEPARATOR + cellValue.getNumberValue());  
    125.                     }  
    126.                     break;  
    127.                 case Cell.CELL_TYPE_STRING:  
    128.                     sb.append(SEPARATOR + cellValue.getStringValue());  
    129.                     break;  
    130.                 case Cell.CELL_TYPE_FORMULA:  
    131.                     break;  
    132.                 case Cell.CELL_TYPE_BLANK:  
    133.                     break;  
    134.                 case Cell.CELL_TYPE_ERROR:  
    135.                     break;  
    136.                 default:  
    137.                     break;  
    138.                 }  
    139.             }  
    140.             list.add(sb.toString());  
    141.         }  
    142.         return list;  
    143.     }  
    144. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaPOI一个用于读取和写入Microsoft Office格式文件(如Excel、Word和PowerPoint)的开源Java库。使用JavaPOI可以实现Excel的导入导出操作。下面是一个简单的示例代码,演示如何使用JavaPOI实现Excel的导入导出功能: 1. 导入Excel文件: ```java import org.apache.poi.ss.usermodel.*; public class ExcelImporter { public static void main(String[] args) { try { Workbook workbook = WorkbookFactory.create(new File("path/to/excel/file.xlsx")); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { // 处理单元格数据 String cellValue = cell.getStringCellValue(); System.out.print(cellValue + "\t"); } System.out.println(); } workbook.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 导出Excel文件: ```java import org.apache.poi.ss.usermodel.*; public class ExcelExporter { public static void main(String[] args) { try { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建表头 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("Name"); headerRow.createCell(1).setCellValue("Age"); headerRow.createCell(2).setCellValue("Email"); // 写入数据 Row dataRow = sheet.createRow(1); dataRow.createCell(0).setCellValue("John Doe"); dataRow.createCell(1).setCellValue(25); dataRow.createCell(2).setCellValue("johndoe@example.com"); FileOutputStream outputStream = new FileOutputStream("path/to/excel/file.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码演示了使用JavaPOI导入导出Excel文件的基本操作。你可以根据自己的需求进行适当的修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值