Excel导入导出

Excel导入导出

 

        摘要:简单的基于Apache的POI的Excel的导入、导出。仅作基础操作、功能需要的可以自己根据自己的需求添加自己的实现。

 

一:简介

 

        在实际项目中经常会有关于Excel的操作、从Excel中读取数据导入到数据库、从数据库中导出数据生成Excel表格等等。这里不是一个全套的拿来就能用的工具。而是简单的导入、导出Excel的数据功能、没有牵扯到样式等等。      

POI是Apache提供的用于操作Microsoft的office的一套办公软件、比如Word、Excel、ppt等、这里仅仅使用POI操作Excel。

 

二:具体导入导出

 

        1、首先是去Apache官网下载POI所需要的jar包——网址:http://poi.apache.org/download.html 、最新版本到了3.10。不再详细介绍组件的含义、有兴趣的可以自己看官网上的说明。

        2、建立java项目(web项目后面有补充):

        3、两个简单导入导出类

                a)       ExcelReader:


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Description:Excel数据读取简单工具类,POI实现,兼容Excel2003,及Excel2007 
  3.  **/  
  4. package com.chy.excel.utils;  
  5.   
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.util.ArrayList;  
  11. import java.util.List;  
  12. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
  13. import org.apache.poi.ss.usermodel.Cell;  
  14. import org.apache.poi.ss.usermodel.DateUtil;  
  15. import org.apache.poi.ss.usermodel.Row;  
  16. import org.apache.poi.ss.usermodel.Sheet;  
  17. import org.apache.poi.ss.usermodel.Workbook;  
  18. import org.apache.poi.ss.usermodel.WorkbookFactory;  
  19.   
  20. public class ExcelReader {  
  21.     Workbook wb = null;  
  22.     List<String[]> dataList = new ArrayList<String[]>(100);  
  23.   
  24.     public ExcelReader(InputStream is) {  
  25.         try {  
  26.             wb = WorkbookFactory.create(is);  
  27.         } catch (InvalidFormatException e) {  
  28.             e.printStackTrace();  
  29.         } catch (IOException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33.   
  34.     public ExcelReader(String path) {  
  35.         try {  
  36.             InputStream inp = new FileInputStream(path);  
  37.             wb = WorkbookFactory.create(inp);  
  38.         } catch (FileNotFoundException e) {  
  39.             e.printStackTrace();  
  40.         } catch (InvalidFormatException e) {  
  41.             e.printStackTrace();  
  42.         } catch (IOException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.   
  46.     }  
  47.   
  48.     /** 
  49.      * 取Excel所有数据,包含header 
  50.      */  
  51.     public List<String[]> getAllData(int sheetIndex) {  
  52.         int columnNum = 0;  
  53.         Sheet sheet = wb.getSheetAt(sheetIndex);  
  54.         if (sheet.getRow(0) != null) {  
  55.             columnNum = sheet.getRow(0).getLastCellNum()  
  56.                     - sheet.getRow(0).getFirstCellNum();  
  57.         }  
  58.         if (columnNum > 0) {  
  59.             for (Row row : sheet) {  
  60.                 String[] singleRow = new String[columnNum];  
  61.                 int n = 0;  
  62.                 for (int i = 0; i < columnNum; i++) {  
  63.                     Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);  
  64.                     switch (cell.getCellType()) {  
  65.                     case Cell.CELL_TYPE_BLANK:  
  66.                         singleRow[n] = "";  
  67.                         break;  
  68.                     case Cell.CELL_TYPE_BOOLEAN:  
  69.                         singleRow[n] = Boolean.toString(cell  
  70.                                 .getBooleanCellValue());  
  71.                         break;  
  72.                     // 数值  
  73.                     case Cell.CELL_TYPE_NUMERIC:  
  74.                         if (DateUtil.isCellDateFormatted(cell)) {  
  75.                             singleRow[n] = String.valueOf(cell  
  76.                                     .getDateCellValue());  
  77.                         } else {  
  78.                             cell.setCellType(Cell.CELL_TYPE_STRING);  
  79.                             String temp = cell.getStringCellValue();  
  80.                             // 判断是否包含小数点,如果不含小数点,则以字符串读取,如果含小数点,则转换为Double类型的字符串  
  81.                             if (temp.indexOf(".") > -1) {  
  82.                                 singleRow[n] = String.valueOf(new Double(temp))  
  83.                                         .trim();  
  84.                             } else {  
  85.                                 singleRow[n] = temp.trim();  
  86.                             }  
  87.                         }  
  88.                         break;  
  89.                     case Cell.CELL_TYPE_STRING:  
  90.                         singleRow[n] = cell.getStringCellValue().trim();  
  91.                         break;  
  92.                     case Cell.CELL_TYPE_ERROR:  
  93.                         singleRow[n] = "";  
  94.                         break;  
  95.                     case Cell.CELL_TYPE_FORMULA:  
  96.                         cell.setCellType(Cell.CELL_TYPE_STRING);  
  97.                         singleRow[n] = cell.getStringCellValue();  
  98.                         if (singleRow[n] != null) {  
  99.                             singleRow[n] = singleRow[n].replaceAll("#N/A""")  
  100.                                     .trim();  
  101.                         }  
  102.                         break;  
  103.                     default:  
  104.                         singleRow[n] = "";  
  105.                         break;  
  106.                     }  
  107.                     n++;  
  108.                 }  
  109.                 if ("".equals(singleRow[0])) {  
  110.                     continue;  
  111.                 }// 如果第一行为空,跳过  
  112.                 dataList.add(singleRow);  
  113.             }  
  114.         }  
  115.         return dataList;  
  116.     }  
  117.   
  118.     /** 
  119.      * 返回Excel最大行index值,实际行数要加1 
  120.      */  
  121.     public int getRowNum(int sheetIndex) {  
  122.         Sheet sheet = wb.getSheetAt(sheetIndex);  
  123.         return sheet.getLastRowNum();  
  124.     }  
  125.   
  126.     /** 
  127.      * 返回数据的列数 
  128.      */  
  129.     public int getColumnNum(int sheetIndex) {  
  130.         Sheet sheet = wb.getSheetAt(sheetIndex);  
  131.         Row row = sheet.getRow(0);  
  132.         if (row != null && row.getLastCellNum() > 0) {  
  133.             return row.getLastCellNum();  
  134.         }  
  135.         return 0;  
  136.     }  
  137.   
  138.     /** 
  139.      * 获取某一行数据 计数从0开始,rowIndex为0代表header行 
  140.      */  
  141.     public String[] getRowData(int sheetIndex, int rowIndex) {  
  142.         String[] dataArray = null;  
  143.         if (rowIndex > this.getColumnNum(sheetIndex)) {  
  144.             return dataArray;  
  145.         } else {  
  146.             dataArray = new String[this.getColumnNum(sheetIndex)];  
  147.             return this.dataList.get(rowIndex);  
  148.         }  
  149.   
  150.     }  
  151.   
  152.     /** 
  153.      * 获取某一列数据 
  154.      */  
  155.     public String[] getColumnData(int sheetIndex, int colIndex) {  
  156.         String[] dataArray = null;  
  157.         if (colIndex > this.getColumnNum(sheetIndex)) {  
  158.             return dataArray;  
  159.         } else {  
  160.             if (this.dataList != null && this.dataList.size() > 0) {  
  161.                 dataArray = new String[this.getRowNum(sheetIndex) + 1];  
  162.                 int index = 0;  
  163.                 for (String[] rowData : dataList) {  
  164.                     if (rowData != null) {  
  165.                         dataArray[index] = rowData[colIndex];  
  166.                         index++;  
  167.                     }  
  168.                 }  
  169.             }  
  170.         }  
  171.         return dataArray;  
  172.     }  
  173. }  


                b)       ExcelWriter:


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.chy.excel.bean;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class StudentInfo {  
  6.     private int stuId;  
  7.     private String stuName;  
  8.     private double stuScore;  
  9.     private Date birthDay;  
  10.   
  11.     public StudentInfo() {  
  12.         super();  
  13.     }  
  14.   
  15.   
  16.     public StudentInfo(int stuId, String stuName, double stuScore, Date birthDay) {  
  17.         super();  
  18.         this.stuId = stuId;  
  19.         this.stuName = stuName;  
  20.         this.stuScore = stuScore;  
  21.         this.birthDay = birthDay;  
  22.     }  
  23.   
  24.   
  25.     public Date getBirthDay() {  
  26.         return birthDay;  
  27.     }  
  28.   
  29.   
  30.     public void setBirthDay(Date birthDay) {  
  31.         this.birthDay = birthDay;  
  32.     }  
  33.   
  34.   
  35.     public int getStuId() {  
  36.         return stuId;  
  37.     }  
  38.   
  39.     public void setStuId(int stuId) {  
  40.         this.stuId = stuId;  
  41.     }  
  42.   
  43.     public String getStuName() {  
  44.         return stuName;  
  45.     }  
  46.   
  47.     public void setStuName(String stuName) {  
  48.         this.stuName = stuName;  
  49.     }  
  50.   
  51.     public double getStuScore() {  
  52.         return stuScore;  
  53.     }  
  54.   
  55.     public void setStuScore(double stuScore) {  
  56.         this.stuScore = stuScore;  
  57.     }  
  58. }  

                c)       ExcelWriter:


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.chy.excel.utils;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStream;  
  6. import java.lang.reflect.Field;  
  7. import java.lang.reflect.Method;  
  8. import java.text.SimpleDateFormat;  
  9. import java.util.Date;  
  10. import java.util.List;  
  11.   
  12. import org.apache.poi.hssf.usermodel.HSSFCell;  
  13. import org.apache.poi.hssf.usermodel.HSSFRow;  
  14. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  15. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  16.   
  17. /** 
  18.  *  
  19.  * @author andyChen 
  20.  *  
  21.  * @param <T> 
  22.  *            数据类型泛型 
  23.  */  
  24. @SuppressWarnings("unchecked")  
  25. public class ExcelWriter<T> {  
  26.     private String excelSavePath;  
  27.     private List<T> list;  
  28.     private String excelName;  
  29.     private String[] titles;  
  30.   
  31.     /** 
  32.      * 构造方法的形式将Excel保存地址、名称、数据传入 
  33.      *  
  34.      * @param excelSavePath 
  35.      *            Excel保存地址 
  36.      * @param excelName 
  37.      *            Excel保存名称 
  38.      * @param list 
  39.      *            写入Excel中的数据 
  40.      */  
  41.     public ExcelWriter(String excelSavePath, String excelName, List<T> list,  
  42.             String[] titles) {  
  43.         // 参数校验  
  44.         if (list.size() == 0) {  
  45.             throw new IllegalArgumentException(  
  46.                     "the argument of list is illegal");  
  47.         }  
  48.   
  49.         // 如果标题与属性个数不匹配、则抛异常。  
  50.         Class t = list.get(0).getClass();  
  51.         Field[] filed = t.getDeclaredFields();  
  52.         if (filed.length != titles.length) {  
  53.             throw new IllegalArgumentException(  
  54.                     "title can not match the context");  
  55.         }  
  56.   
  57.         // 初始化数据  
  58.         this.excelSavePath = excelSavePath;  
  59.         this.list = list;  
  60.         this.excelName = excelName;  
  61.         this.titles = titles;  
  62.     }  
  63.   
  64.     /** 
  65.      * 将初始化好的数据写入到Excel中 
  66.      * @return 是否写入成功? 
  67.      */  
  68.     public boolean writerExcel() {  
  69.         HSSFWorkbook wb = null;  
  70.         OutputStream os = null;  
  71.         try {  
  72.             wb = new HSSFWorkbook();  
  73.             // 可以指定Sheet名称、可以使用默认的  
  74.             HSSFSheet sheet = wb.createSheet();  
  75.   
  76.             // 将第一行设置为标题  
  77.             HSSFRow titleRow = sheet.createRow(0);  
  78.             for (int j = 0; j < titles.length; j++) {  
  79.                 HSSFCell titleCell = titleRow.createCell(j);  
  80.                 titleCell.setCellValue(titles[j]);  
  81.             }  
  82.   
  83.             // 根据记录数创建行、一条记录对应一行  
  84.             for (int i = 0; i < list.size(); i++) {  
  85.                 // 注意是从第二行开始添加数据、第一行是标题  
  86.                 HSSFRow row = sheet.createRow(i + 1);  
  87.                 // 获取list中JavaBean的属性数  
  88.                 T bean = list.get(i);  
  89.   
  90.                 // 反射拿到T中所有方法、包括私有方法  
  91.                 Class t = bean.getClass();  
  92.                 Field[] filed = t.getDeclaredFields();  
  93.   
  94.                 // 反射获取当前对象每个属性的值、设置到对应的列中。  
  95.                 for (int j = 0; j < filed.length; j++) {  
  96.                     HSSFCell cell = row.createCell(j);  
  97.                     Field field = filed[j];  
  98.                     String fieldName = field.getName();  
  99.                     String getMethodNameByFieldName = "get"  
  100.                             + fieldName.substring(01).toUpperCase()  
  101.                             + fieldName.substring(1);  
  102.                     Method method = t.getMethod(getMethodNameByFieldName);  
  103.                     Object value = method.invoke(bean);  
  104.                     setValue(value, cell);  
  105.                 }  
  106.             }  
  107.             os = new FileOutputStream(excelSavePath + "/" + excelName + ".xls");  
  108.             wb.write(os);  
  109.             // 会先执行finally中代码、然后再执行return。  
  110.             return true;  
  111.         } catch (Exception e) {  
  112.             e.printStackTrace();  
  113.         } finally {  
  114.             // 关闭流  
  115.             if (os != null) {  
  116.                 try {  
  117.                     os.close();  
  118.                 } catch (IOException e) {  
  119.                     e.printStackTrace();  
  120.                 }  
  121.             }  
  122.         }  
  123.         return false;  
  124.     }  
  125.   
  126.     /** 
  127.      * 设置value值、可以按照这种形式来处理自己想处理的value。 
  128.      *  
  129.      * @param value 
  130.      *            要写入Excel的值 
  131.      * @param cell 
  132.      *            value被写入的行 
  133.      */  
  134.     private void setValue(Object value, HSSFCell cell) {  
  135.         String textValue = value.toString();  
  136.         if (value instanceof Date) {  
  137.             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  138.             textValue = sdf.format(value);  
  139.         }  
  140.         cell.setCellValue(textValue);  
  141.     }  
  142. }  

        4、测试类——Client:


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.chy.excel.client;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.util.ArrayList;  
  6. import java.util.Arrays;  
  7. import java.util.Date;  
  8. import java.util.List;  
  9.   
  10. import com.chy.excel.bean.StudentInfo;  
  11. import com.chy.excel.utils.ExcelReader;  
  12. import com.chy.excel.utils.ExcelWriter;  
  13.   
  14. public class Client {  
  15.     private static String excelSavePath = "F:";  
  16.     private static String excelName = "student_information";  
  17.   
  18.     public static void main(String[] args) {  
  19.   
  20.         System.out.println(exportExcel());  
  21.         importExcel();  
  22.           
  23.     }  
  24.       
  25.     private static void importExcel(){  
  26.         //ExcelReader reader = new ExcelReader("F:\\student_information.xls"); 效果一样。  
  27.         ExcelReader reader;  
  28.         try {  
  29.             reader = new ExcelReader(new FileInputStream("F:\\student_information.xls"));  
  30.             List<String[]> list = reader.getAllData(0);  
  31.             for (String[] data : list) {  
  32.                 System.out.println(Arrays.toString(data));  
  33.             }  
  34.         } catch (FileNotFoundException e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.     }  
  38.   
  39.     /** 
  40.      * 导出Excel 
  41.      *  
  42.      * @return 导出成功? 
  43.      */  
  44.     private static boolean exportExcel() {  
  45.         String[] titles = { "学号""姓名""分数""出生日期" };  
  46.         List<StudentInfo> list = new ArrayList<StudentInfo>();  
  47.         list.add(new StudentInfo(1"chy"90.3new Date()));  
  48.         list.add(new StudentInfo(2"mxx"70.3new Date()));  
  49.         ExcelWriter<StudentInfo> ew = new ExcelWriter<StudentInfo>(  
  50.                 excelSavePath, excelName, list, titles);  
  51.         return ew.writerExcel();  
  52.     }  
  53. }  

三:补充


       项目中许多时候都是在web项目中来使用Excel的、但是从上面可以知道、java项目与web项目的区别无非就是环境不一样、我们对与Excel的操作、只需知道关于他的流或者文件在服务器上的存放的位置即可。

       在web项目、比如ssh项目总、Excel的导入就可以按照普通的文件上传的方式来处理、jsp页面一个form表单、有个type为file的input标签。提交之前校验一下是不是Excel文件、是的话让他提交、我们在struts2的Action中定义一个同名的File类型的私有属性、给他getXXX、setXXX方法、这样、struts2就会将文件上传到服务器、我们通过File来获取流还不是 a pice of cake?下面就是java一样的操作了。

       下载的话就是使用数据构造Excel、完成之后和常见下载文件一样、提供流、使用Response流输出就ok。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值