导入导出

   <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
public class ExcelHelper<T> {

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

    private List<T> data;

    private String[] titles;

    private String[] properties;

    private HSSFWorkbook workbook;

    public ExcelHelper(List<T> 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<T> 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<T>();
            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<T> 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<Point> 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<Point> points = helper.getData();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值