当前位置: 移动技术网 > IT编程>开发语言>Java > poi-excel导入导出

poi-excel导入导出

2018年10月17日  | 移动技术网IT编程  | 我要评论

鬼舞乾坤txt下载,诸神之战1在线观看,洛桑邓珠

一、添加依赖

        <dependency>
            <groupid>org.apache.poi</groupid>
            <artifactid>poi-scratchpad</artifactid>
            <version>3.17</version>
        </dependency>

  

二、工具类

import lombok.extern.slf4j.slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.cell;
import org.apache.poi.ss.usermodel.row;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.commons.commonsmultipartfile;

import java.io.*;
import java.lang.reflect.field;
import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import java.lang.reflect.type;
import java.text.simpledateformat;
import java.util.*;


@slf4j
public class excelhelper<t> {
    //构造方法
    public excelhelper() {
    }

    class<t> clazz;

    public class<t> getclazz() {
        return clazz;
    }

    public void setclazz(class<t> clazz) {
        this.clazz = clazz;
    }


    /**
     * 读excel文件,获取信息集合
     *filepath:文件所在目录;name:文件名称;fieldmap:目标类需要导入的字段
     * @param filepath
     * @return
     */
    public list<t> getexcelinfo(string filepath,string name,map fieldmap,multipartfile mfile) {
        //把spring文件上传的multipartfile转换成commonsmultipartfile类型
        commonsmultipartfile cf = (commonsmultipartfile) mfile; //获取本地存储路径

        file file = new file(filepath);
        //创建一个目录 (它的路径名由当前 file 对象指定,包括任一必须的父路径。)
        if (!file.exists()) file.mkdirs();
        //新建一个文件
        string newfilepath=filepath+name;
        file file1 = new file(newfilepath);
        //将上传的文件写入新建的文件中
        try {
            cf.getfileitem().write(file1);
        } catch (exception e) {
            log.error("readexcel:" + e);
            e.printstacktrace();
        }
        list<t> dist = new arraylist<t>();
        try {
            fileinputstream in = new fileinputstream(file1);
            hssfworkbook book = new hssfworkbook(in);
            // // 得到第一页
            hssfsheet sheet = book.getsheetat(0);
            // // 得到第一面的所有行
            iterator<row> row = sheet.rowiterator();
            // 获取标题map
            map titlemap = gettitlemap(row);
            while (row.hasnext()) {
                t tobject = clazz.newinstance();
                // 标题下的第一行
                row rown = row.next();
                int k = 0;
                // 遍历一行的列
                for (int j = 0; j < rown.getlastcellnum() + 1; j++) {
                    cell cell = rown.getcell(j);
                    if (cell == null) {
                        k++;
                        continue;
                    }
                    // 得到此列的对应的标题
                    string titlestring = (string) titlemap.get(k);
                    // 如果这一列的标题和类中的某一列的annotation相同,那么则调用此类的的set方法,进行设值
                    if (fieldmap.containskey(titlestring)) {
                        method setmethod = (method) fieldmap.get(titlestring);
                        setdata(tobject, cell, setmethod);
                    }
                    k++;
                }
                dist.add(tobject);
            }
        } catch (exception e) {
            log.error(e.tostring());
        }
        return dist;
    }


    private map gettitlemap(iterator<row> row) {

        row title = row.next();
        // 得到第一行的所有列
        iterator<cell> celltitle = title.celliterator();
        // 将标题的文字内容放入到一个map中。
        map titlemap = new hashmap();
        // 从标题第一列开始
        int i = 0;
        // 循环标题所有的列
        while (celltitle.hasnext()) {
            cell cell = celltitle.next();
            string value = cell.getstringcellvalue();
            // 还是把表头trim一下
            value = value.trim();
            titlemap.put(i, value);
            i = i + 1;
        }
        return titlemap;
    }


    private void setdata(t tobject, cell cell, method setmethod) throws illegalaccessexception, invocationtargetexception {
        // 得到setter方法的参数
        type[] ts = setmethod.getgenericparametertypes();
        // 只要一个参数
        string xclass = ts[0].tostring();
        // 判断参数类型
        try {
            switch (cell.getcelltypeenum()) {
                // 数字
                case numeric:
                    if ("class java.lang.string".equals(xclass)) {
                        if ((cell.getnumericcellvalue() + "").indexof(".") > 0) {
                            setmethod.invoke(tobject, (cell.getnumericcellvalue() + "").substring(0, (cell.getnumericcellvalue() + "").lastindexof(".")));
                        }
                    } else if ("class java.lang.integer".equals(xclass)) {
                        setmethod.invoke(tobject, (int) cell.getnumericcellvalue());
                    } else if ("int".equals(xclass)) {
                        setmethod.invoke(tobject, (int) cell.getnumericcellvalue());
                    } else if ("class java.lang.long".equals(xclass)) {
                        long temp = (long) cell.getnumericcellvalue();
                        setmethod.invoke(tobject, temp);
                    }
                    break;
                // 字符串
                case string:
                    if ("class java.lang.integer".equals(xclass)) {
                        setmethod.invoke(tobject, integer.parseint(cell.getstringcellvalue()));
                    } else if ("class java.lang.string".equals(xclass)) {
                        setmethod.invoke(tobject, cell.getstringcellvalue().trim());
                    } else if ("int".equals(xclass)) {
                        int temp = integer.parseint(cell.getstringcellvalue());
                        setmethod.invoke(tobject, temp);
                    } else if ("class java.lang.long".equals(xclass)) {
                        long temp = long.parselong(cell.getstringcellvalue());
                        setmethod.invoke(tobject, temp);
                    }
                    break;
                // boolean
                case boolean:
                    boolean boolname = true;
                    if ("否".equals(cell.getstringcellvalue())) {
                        boolname = false;
                    }
                    setmethod.invoke(tobject, boolname);
                    break;
                // 公式
                case formula:
                    log.info(cell.getcellformula() + "   ");
                    break;
                // 空值
                case blank:
                    log.info(" ");
                    break;
                // 故障
                case error:
                    log.info(" ");
                    break;
                default:
                    log.info("未知类型   ");
                    break;
            }
        } catch (exception e) {
            // 转换出错
            log.error(e.tostring());
            throw e;
        }
    }


    // 得到目标类需要导入的字段
    public map getfieldmap(string[] fileds) throws nosuchmethodexception {
        field[] filed = clazz.getdeclaredfields();
        map fieldmap = new hashmap();
        // 循环读取所有字段
        for (int i = 0; i < filed.length; i++) {
            field f = filed[i];
            for(int j=0;j<fileds.length;j++){
                string fd=fileds[j];
                if(f.getname().equals(fd)){
                    string setmethodname = "set"
                            + f.getname().substring(0, 1).touppercase()
                            + f.getname().substring(1);
                    method setmethod = clazz.getmethod(setmethodname,
                            new class[]{f.gettype()});
                    fieldmap.put(f.getname(), setmethod);
                }

            } }
        return fieldmap;
    }

    //导出excel
    public  string export(string basepath,string excelpath,string [][] content,string[] title,string sheetname,string filename){
        outputstream os=null;

        try {
            filename=new simpledateformat("yyyy-mm-dd").format(new date())+"/"+filename;
            file folderfile=new file(basepath+excelpath+new simpledateformat("yyyy-mm-dd").format(new date()));
            if(!folderfile.exists()){
                folderfile.mkdir();
            }
            os = new fileoutputstream(new file(basepath+excelpath + filename));
            hssfworkbook wb = gethssfworkbook(sheetname, title, content, null);
            wb.write(os);
            os.flush();
            os.close();
        }catch (exception e){
            e.printstacktrace();

        }finally {
            os=null;
        }
        return excelpath+filename;
    }


    /**
     * 导出excel
     * @param sheetname sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb hssfworkbook对象
     * @return
     */
    private  hssfworkbook gethssfworkbook(string sheetname,string []title,string [][]values, hssfworkbook wb){

        // 第一步,创建一个hssfworkbook,对应一个excel文件
        if(wb == null){
            wb = new hssfworkbook();
        }

        // 第二步,在workbook中添加一个sheet,对应excel文件中的sheet
        hssfsheet sheet = wb.createsheet(sheetname);

        // 第三步,在sheet中添加表头第0行,注意老版本poi对excel的行数列数有限制
        hssfrow row = sheet.createrow(0);

        // 第四步,创建单元格,并设置值表头 设置表头居中
        hssfcellstyle style = wb.createcellstyle();
        //style.setalignment(hssfcellstyle.align_center); // 创建一个居中格式

        //声明列对象
        hssfcell cell = null;

        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createcell(i);
            cell.setcellvalue(title[i]);
            cell.setcellstyle(style);
        }

        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createrow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                row.createcell(j).setcellvalue(values[i][j]);
            }
        }
        return wb;
    }
}

  

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网