导入导出

   
            org.apache.poi
            poi
            3.17
        
public class ExcelHelper {

    private static final Log logger = LogFactory.getLog(ExcelHelper.class);

    private List data;

    private String[] titles;

    private String[] properties;

    private HSSFWorkbook workbook;

    public ExcelHelper(List data, String[] titles, String[] properties){
        if(data == null || titles == null || properties == null || titles.length == 0 || properties.length == 0 || titles.length != properties.length){
            throw new IllegalArgumentException("illegal argument");
        }
        this.data = data;
        this.titles = titles;
        this.properties = properties;
        this.workbook = toExcel();
    }


    public ExcelHelper(InputStream in, Class clazz, String[] properties){
        if(in == null || clazz == null || properties == null || properties.length == 0 ){
            throw new IllegalArgumentException("illegal argument");
        }
        try {
            this.properties = properties;
            int columnNum = properties.length;
            this.titles = new String[columnNum];
            this.workbook = new HSSFWorkbook(in);
            HSSFSheet sheet = workbook.getSheetAt(0);
            HSSFRow titleRow = sheet.getRow(0);
            for(int i = 0; i < columnNum; i++){
                HSSFCell cell = titleRow.getCell(i);
                this.titles[i] = cell.getStringCellValue();
            }


            this.data = new ArrayList();
            Class[] propertiesTypes = new Class[columnNum];
            for (int i = 0; i < columnNum; i++){
                propertiesTypes[i] = clazz.getDeclaredField(properties[i]).getType();
            }

            int length = sheet.getLastRowNum();
            for(int i = 1; i <= length; i++){
                HSSFRow row = sheet.getRow(i);
                T bean = clazz.newInstance();
                for(int j = 0; j < columnNum; j++){
                    HSSFCell cell = row.getCell(j);
                    String propertyType = propertiesTypes[j].getName();
                    String propertyName = properties[j];
                    if(propertyType.equals("java.util.Date")){
                        BeanUtils.setProperty(bean, propertyName, cell.getDateCellValue());
                    }else{
                        BeanUtils.setProperty(bean, propertyName, cell.getStringCellValue());
                    }
                }

                this.data.add(bean);
            }
        } catch (Exception e) {
            throw new RuntimeException("parse excel file error", e);
        }
    }

    public List getData() {
        return data;
    }

    public String[] getTitles() {
        return titles;
    }

    public String[] getProperties() {
        return properties;
    }

    public int getColumnNum(){
        return this.titles.length;
    }

    /**
     * 下载excel文件
     * @return
     */
    public void download(HttpServletRequest request, HttpServletResponse response, String fileName){
        try{
            response.setCharacterEncoding("UTF-8");
            fileName = fileName + ".xls";
            fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

            response.setContentType("application/x-msdownload");
            response.setContentType("application/vnd.ms-excel");
            response.setContentType("application/octet-stream;charset=UTF-8;");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            workbook.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 列表转化为excel对象
     * @return
     */
    public HSSFWorkbook toExcel(){
        int columnNum = getColumnNum();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();

        HSSFRow titleRow = sheet.createRow(0);
        for (int i = 0; i < columnNum; i++){
            HSSFCell cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }

        for(int i = 0; i < data.size(); i++){
            Object object = data.get(i);
            HSSFRow row = sheet.createRow(i + 1);
            for (int j = 0; j < columnNum; j++){
                String propertyName = properties[j];
                HSSFCell cell = row.createCell(j);
                try {
                    Object propertyValue = PropertyUtils.getProperty(object, propertyName);
                    if (propertyValue instanceof Date){
                        cell.setCellValue((Date)propertyValue);
                    }else if (propertyValue instanceof Calendar){
                        cell.setCellValue((Calendar)propertyValue);
                    }else {
                        cell.setCellValue(propertyValue.toString());
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }

        return workbook;
    }


    public static void main(String[] args) throws FileNotFoundException {
        InputStream in = new FileInputStream(new File("D:\\1.xls"));
        String[] properties = new String[]{"pointCode", "pointName"};
        ExcelHelper helper = new ExcelHelper(in, Point.class, properties);
        List points = helper.getData();
        logger.info("import point number is" + points.size() + ", content :" + JSON.toJSONString(points));
    }

导出

   String[] titles = new String[]{"", "", "", ""};
        String[] properties = new String[]{"","", "", ""};
        String fileName = pointBatch.getName();
        ExcelHelper helper = new ExcelHelper(points, titles, properties);
        helper.download(request, response, fileName);

导入

  String[] properties = new String[]{"", ""};
        ExcelHelper helper = new ExcelHelper(file.getInputStream(), Point.class, properties);
        List points = helper.getData();


你可能感兴趣的:(导入导出)