JAVA 使用Apache POI 百万数据导出 Excel表格与Excel转Java对象的工具类

工具类

import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class ExcelUtil implements Serializable {

    private static int lastRow=50000;
    /**
     * List<List<String>>转excle,最多写65535行
     *
     * @param list
     * @return
     */
    public static XSSFWorkbook getExcel(List<List<String>> list) {

        XSSFWorkbook workbook = new XSSFWorkbook();//表格对象
        XSSFSheet sheet = workbook.createSheet();//第一个sheet(工作表)
        sheet.setDefaultColumnWidth(15);

        for (int i = 0; i < list.size(); i++) {
            List<String> strings = list.get(i);

            XSSFRow row = sheet.createRow(i);//0行

            for (int j = 0; j < strings.size(); j++) {
                String s = strings.get(j);


                row.createCell(j).setCellValue(s);//0列


            }
        }

        return workbook;
    }

    /**
     * 直接new新的excle写,最多写65535行
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T> XSSFWorkbook exportExcel(List<T> list) {
        XSSFWorkbook workbook = new XSSFWorkbook();//表格对象
        XSSFSheet sheet = workbook.createSheet();//第一个sheet(工作表)
        sheet.setDefaultColumnWidth(15);
        int a = 0;//为了设置表头的计数
        int b = 0;//为了跳过没有注解的字段

        for (int j = 0; j < list.size(); j++) {
            T t = list.get(j);
            XSSFRow row = null;
            if (a == 0) {
                row = sheet.createRow(j);//0行

            } else {
                row = sheet.createRow(j + 1);//0行
            }
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (fields[i].isAnnotationPresent(Excel.class)) {
                    if (a == 0) {
                        Excel annotation = fields[i].getAnnotation(Excel.class);
                        row.createCell(i - b).setCellValue(annotation.title());//0列


                    } else {

                        //设置是否允许访问,不是修改原来的访问权限修饰词。
                        fields[i].setAccessible(true);
                        String s = null;
                        try {
                            s = String.valueOf(fields[i].get(t));
                        } catch (IllegalAccessException e) {

                            e.printStackTrace();
                        }
                        if (s == null || "null".equals(s)) {
                            s = "";
                        }
                        row.createCell(i - b).setCellValue(s);//0列
                    }
                } else {
                    b++;

                }
                if (a == 0 && i == fields.length - 1) {
                    a = 1;
                    j--;
                }
            }
            b = 0;
        }
        return workbook;
    }

    /**
     * 续写excle,最多超过100w条自动新增Sheet
     *
     * @param list
     * @param workbook
     * @param <T>
     * @return
     */
    public static <T> SXSSFWorkbook exportExcelBySXSS(List<T> list, SXSSFWorkbook workbook) {
        int a = 0;//为了设置表头的计数
        int b = 0;//为了跳过没有注解的字段
        int c = list.size();
        int d = 0;//续写的计数
        SXSSFSheet sheet = null;
        if (workbook == null) {
            workbook = new SXSSFWorkbook();//表格对象
            sheet = workbook.createSheet();//第一个sheet(工作表)
        } else {
            sheet = workbook.getSheetAt(workbook.getNumberOfSheets() - 1);
            a = 1;//为了设置表头的计数
            b = 0;//为了跳过没有注解的字段
            d = sheet.getLastRowNum();//续写的计数
            c = c + d;

        }
        sheet.setDefaultColumnWidth(15);
        int temp = 0;
        for (int j = d; j < c; j++) {
            T t = list.get(j - d);
            SXSSFRow row = null;
            if (a == 0) {
                row = sheet.createRow(j - temp);//0行

            } else {
                row = sheet.createRow(j + 1 - temp);//0行
            }
            int lastRowNum = workbook.getSheetAt(workbook.getNumberOfSheets() - 1).getLastRowNum();
            if (lastRowNum >= lastRow) {
                temp = j;
                a = 0;
                sheet = workbook.createSheet();
                row = sheet.createRow(0);//0行
            }
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (fields[i].isAnnotationPresent(Excel.class)) {
                    if (a == 0) {
                        Excel annotation = fields[i].getAnnotation(Excel.class);
                        row.createCell(i - b).setCellValue(annotation.title());//0列

                    } else {

                        //设置是否允许访问,不是修改原来的访问权限修饰词。
                        fields[i].setAccessible(true);
                        String s = null;
                        try {
                            PropertyDescriptor descriptor = new PropertyDescriptor(fields[i].getName(), t.getClass());
                            Method readMethod = descriptor.getReadMethod();
                            Object o = readMethod.invoke(t);
                            s = String.valueOf(o);//fields[i].get(t)
                        } catch (Exception e) {

                            e.printStackTrace();
                        }

                        if (s == null || "null".equals(s)) {
                            s = "";
                        }
                        row.createCell(i - b).setCellValue(s);//0列
                    }
                } else {
                    b++;

                }

                if (a == 0 && i == fields.length - 1) {
                    a = 1;
                    j--;
                }
            }
            b = 0;
        }

        return workbook;
    }


    /**
     * excel转对象,支持多个sheet,每个sheet必须要有表头 最多65535
     *
     * @param
     * @param t
     * @param <T>
     * @return
     * @throws Exception
     */
       public static <T> List<T> readExcel(XSSFWorkbook workbook,  Class<T> t) throws Exception {
      int count=  workbook.getNumberOfSheets() ;
        List<T> objects = new ArrayList<>();
        for (int temp = 0; temp <count; temp++) {
            XSSFSheet sheet = workbook.getSheetAt(temp);//第一个sheet(工作表)
            int lastRowNum = sheet.getLastRowNum();
            List<String> list = new ArrayList<>();

            if (lastRowNum == 0) {
                return null;
            }

            for (int i = 0; i < 1; i++) {
                XSSFRow row = sheet.getRow(i);
                int lastCellNum = row.getLastCellNum();
                for (int j = 0; j < lastCellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    String s = cell.toString();
                    list.add(s);
                }
            }


            for (int i = 1; i < lastRowNum+1; i++) {
                XSSFRow row = sheet.getRow(i);
                int lastCellNum = row.getLastCellNum();
                Constructor constructor = t.getConstructor();
                T o = (T) constructor.newInstance();
                for (int j = 0; j < lastCellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    String s = cell.toString();

                    // 获取obj类的字节文件对象
                    Class c = o.getClass();
                    Field[] fields = c.getDeclaredFields();
                    for (int k = 0; k < fields.length; k++) {


                        if (fields[k].isAnnotationPresent(Excel.class)) {
                            Excel annotation = fields[k].getAnnotation(Excel.class);
                            String title = annotation.title();
                            if (title.equals(list.get(j))) {
                                // 获取该类的成员变量
                                /*   Field f = c.getDeclaredField(fields[k].getName());*/

// 取消语言访问检查
                                Field f = c.getDeclaredField(fields[k].getName());
                                Class<?> type = f.getType();
                                f.setAccessible(true);
// 给变量赋值
                                Object obj=s;
                                if (type.equals(Integer.class)) {
                                    obj=Integer.valueOf(s);
                                }
                                if (type.equals(Double.class)) {
                                    obj=Double.valueOf(s);
                                }
                                if (type.equals(Long.class)) {
                                    obj=Long.valueOf(s);
                                }
                                if (type.equals(Byte.class)) {
                                    obj=Byte.valueOf(s);
                                }
                                if (type.equals(Short.class)) {
                                    obj=Short.valueOf(s);
                                }
                                if (type.equals(Boolean.class)) {
                                    obj=Boolean.valueOf(s);
                                }
                                if (type.equals(Float.class)) {
                                    obj=Float.valueOf(s);
                                }
                                if (type.equals(BigDecimal.class)) {
                                    obj=BigDecimal.valueOf(Long.valueOf(s));
                                }
                                if (type.equals(Date.class)) {
                                    obj=DateFormat.getInstance().parse(s);
                                }
                                f.set(o, obj);

                            }
                        }

                    }
             }
                objects.add(o);
        }

        }
        return objects;
    }


    /**
     * 续写excle,超过100w条自动新增Sheet,可手动设置dateBase字段转前端展示字段
     *
     * @param list
     * @param workbook
     * @param <T>
     * @return
     */

    public static <T> SXSSFWorkbook exportExcelBySXSS(List<T> list, SXSSFWorkbook workbook, HashMap<String,ExcelTableToString> hashMap) {
        int a = 0;//为了设置表头的计数
        int b = 0;//为了跳过没有注解的字段
        int c = list.size();
        int d = 0;//续写的计数
        SXSSFSheet sheet = null;
        if (workbook == null) {
            workbook = new SXSSFWorkbook();//表格对象
            sheet = workbook.createSheet();//第一个sheet(工作表)
        } else {
            sheet = workbook.getSheetAt(workbook.getNumberOfSheets() - 1);
            a = 1;//为了设置表头的计数
            b = 0;//为了跳过没有注解的字段
            d = sheet.getLastRowNum();//续写的计数
            c = c + d;

        }
        sheet.setDefaultColumnWidth(15);
        int temp = 0;

        for (int j = d; j < c; j++) {
            T t = list.get(j - d);
            SXSSFRow row = null;
            if (a == 0) {
                row = sheet.createRow(j - temp);//0行

            } else {
                row = sheet.createRow(j + 1 - temp);//0行
            }
            int lastRowNum = workbook.getSheetAt(workbook.getNumberOfSheets() - 1).getLastRowNum();
            if (lastRowNum >= lastRow) {
                temp = j;
                a = 0;
                sheet = workbook.createSheet();
                row = sheet.createRow(0);//0行
            }
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (fields[i].isAnnotationPresent(Excel.class)) {
                    Excel annotation = fields[i].getAnnotation(Excel.class);
                    String     title = annotation.title();
                    if (a == 0) {

                        row.createCell(i - b).setCellValue(title);//0列

                    } else {

                        //设置是否允许访问,不是修改原来的访问权限修饰词。
                        fields[i].setAccessible(true);
                        String s = null;
                        try {
                            PropertyDescriptor descriptor = new PropertyDescriptor(fields[i].getName(), t.getClass());
                            Method readMethod = descriptor.getReadMethod();
                            Object o = readMethod.invoke(t);
                            ExcelTableToString excelTableToString = hashMap.get(title);
                            if (excelTableToString!=null){
                                o = excelTableToString.tableToString(o);
                            }
                            s = String.valueOf(o);//fields[i].get(t)
                        } catch (Exception e) {

                            e.printStackTrace();
                        }

                        if (s == null || "null".equals(s)) {
                            s = "";
                        }
                        row.createCell(i - b).setCellValue(s);//0列
                    }
                } else {
                    b++;

                }

                if (a == 0 && i == fields.length - 1) {
                    a = 1;
                    j--;
                }
            }
            b = 0;
        }

        return workbook;
    }


    /**
     * excel表达式写入方式 最多65535
     *   #{}
     * @param
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public static XSSFWorkbook  writeExcel(File file ,HashMap<String,ExcelTableToString> map) throws Exception {

        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));//表格对象
        XSSFSheet sheet = workbook.getSheetAt(0);//第一个sheet(工作表)
        int lastRowNum = sheet.getLastRowNum();

        if (lastRowNum == 0) {
    return null;
        }
        for (int i = 1; i < lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            int lastCellNum = row.getLastCellNum();
            for (int j = 0; j < lastCellNum; j++) {
                XSSFCell cell = row.getCell(j);
                String s = cell.toString();
              if (s!=null&&!"".equals(s)){
                  int n = s.indexOf("#{");
                  int m = s.indexOf("}");
                  if (n!=-1&&m!=-1){
                      String substring = s.substring(n+2, m);
                      ExcelTableToString excelTableToString = map.get(substring);
                      Object o = excelTableToString.tableToString(substring);
                      cell.setCellValue(String.valueOf(o));
                  }

              }

            }

        }

    return  workbook;
    }


    /**
     * 续写excle,超过100w条自动新增Sheet,可手动设置dateBase字段转前端展示字段,手动设置当前续写是否要加表头
     *
     * @param list
     * @param workbook
     * @param <T>
     * @return
     */

    public static <T> SXSSFWorkbook exportExcelBySXSS(List<T> list, SXSSFWorkbook workbook, HashMap<String,ExcelTableToString> hashMap,Boolean flag) {
        int a = 0;//为了设置表头的计数
        int b = 0;//为了跳过没有注解的字段
        int c = list.size();
        int d = 0;//续写的计数
        SXSSFSheet sheet = null;
        if (workbook == null) {
            workbook = new SXSSFWorkbook();//表格对象
            sheet = workbook.createSheet();//第一个sheet(工作表)
        } else {
            sheet = workbook.getSheetAt(workbook.getNumberOfSheets() - 1);
            if (flag!=null&& flag==true){
                a=0;
                flag=false;
            }else {
                a = 1;//为了设置表头的计数
            }
            b = 0;//为了跳过没有注解的字段
            d = sheet.getLastRowNum();//续写的计数
            c = c + d;

        }
        sheet.setDefaultColumnWidth(15);
        int temp = 0;

        for (int j = d; j < c; j++) {
            T t = list.get(j - d);
            SXSSFRow row = null;
            if (a == 0) {
                row = sheet.createRow(j - temp);//0行

            } else {
                row = sheet.createRow(j + 1 - temp);//0行
            }
            int lastRowNum = workbook.getSheetAt(workbook.getNumberOfSheets() - 1).getLastRowNum();
            if (lastRowNum >= lastRow) {
                temp = j;
                a = 0;
                sheet = workbook.createSheet();
                row = sheet.createRow(0);//0行
            }
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (fields[i].isAnnotationPresent(Excel.class)) {
                    Excel annotation = fields[i].getAnnotation(Excel.class);
                    String     title = annotation.title();
                    if (a == 0) {

                        row.createCell(i - b).setCellValue(title);//0列

                    } else {

                        //设置是否允许访问,不是修改原来的访问权限修饰词。
                        fields[i].setAccessible(true);
                        String s = null;
                        try {
                            PropertyDescriptor descriptor = new PropertyDescriptor(fields[i].getName(), t.getClass());
                            Method readMethod = descriptor.getReadMethod();
                            Object o = readMethod.invoke(t);
                            ExcelTableToString excelTableToString = hashMap.get(title);
                            if (excelTableToString!=null){
                                o = excelTableToString.tableToString(o);
                            }
                            s = String.valueOf(o);//fields[i].get(t)
                        } catch (Exception e) {

                            e.printStackTrace();
                        }

                        if (s == null || "null".equals(s)) {
                            s = "";
                        }
                        row.createCell(i - b).setCellValue(s);//0列
                    }
                } else {
                    b++;

                }

                if (a == 0 && i == fields.length - 1) {
                    a = 1;
                    j--;
                }
            }
            b = 0;
        }

        return workbook;
    }


    /**
     * 续写excle,超过5w条自动新增Sheet(最多65535),可手动设置dateBase字段转前端展示字段,手动设置当前续写是否要加表头
     *
     * @param list
     * @param workbook
     * @param <T>
     * @return
     */

    public static <T> XSSFWorkbook exportExcelBySXSS(List<T> list, XSSFWorkbook workbook, HashMap<String,ExcelTableToString> hashMap,Boolean flag) {
        int a = 0;//为了设置表头的计数
        int b = 0;//为了跳过没有注解的字段
        int c = list.size();
        int d = 0;//续写的计数
        XSSFSheet sheet = null;
        if (workbook == null) {
            workbook = new XSSFWorkbook();//表格对象
            sheet = workbook.createSheet();//第一个sheet(工作表)
        } else {
            sheet = workbook.getSheetAt(workbook.getNumberOfSheets() - 1);
            if (flag!=null&& flag==true){
                a=0;
                flag=false;
            }else {
                a = 1;//为了设置表头的计数
            }
            b = 0;//为了跳过没有注解的字段
            d = sheet.getLastRowNum();//续写的计数
            c = c + d;

        }
        sheet.setDefaultColumnWidth(15);
        int temp = 0;

        for (int j = d; j < c; j++) {
            T t = list.get(j - d);
            XSSFRow row = null;
            if (a == 0) {
                row = sheet.createRow(j - temp);//0行

            } else {
                row = sheet.createRow(j + 1 - temp);//0行
            }
            int lastRowNum = workbook.getSheetAt(workbook.getNumberOfSheets() - 1).getLastRowNum();
            if (lastRowNum >= lastRow) {
                temp = j;
                a = 0;
                sheet = workbook.createSheet();
                row = sheet.createRow(0);//0行
            }
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (fields[i].isAnnotationPresent(Excel.class)) {
                    Excel annotation = fields[i].getAnnotation(Excel.class);
                    String     title = annotation.title();
                    if (a == 0) {

                        row.createCell(i - b).setCellValue(title);//0列

                    } else {

                        //设置是否允许访问,不是修改原来的访问权限修饰词。
                        fields[i].setAccessible(true);
                        String s = null;
                        try {
                            PropertyDescriptor descriptor = new PropertyDescriptor(fields[i].getName(), t.getClass());
                            Method readMethod = descriptor.getReadMethod();
                            Object o = readMethod.invoke(t);
                            ExcelTableToString excelTableToString = hashMap.get(title);
                            if (excelTableToString!=null){
                                o = excelTableToString.tableToString(o);
                            }
                            s = String.valueOf(o);//fields[i].get(t)
                        } catch (Exception e) {

                            e.printStackTrace();
                        }

                        if (s == null || "null".equals(s)) {
                            s = "";
                        }
                        row.createCell(i - b).setCellValue(s);//0列
                    }
                } else {
                    b++;

                }

                if (a == 0 && i == fields.length - 1) {
                    a = 1;
                    j--;
                }
            }
            b = 0;
        }

        return workbook;
    }


    public static void main(String[] args) throws Exception {
   

    }
}


注解

@Retention(RetentionPolicy.RUNTIME)
public @interface Excel {

    String title();//表头
}

函数接口

public interface ExcelTableToString {
    public Object tableToString(Object o);
}

实体类

public class User implements Serializable{
   @Excel(title = "id")
   Integer id ;
   @Excel(title = "姓名")
   String name;

   private String sex;
   @Excel(title = "年龄")
   String age;

   public User() {
   }

   public User(Integer id, String name, String age) {
       this.id = id;
       this.name = name;
       this.age = age;
   }

   public String getSex() {
       return sex;
   }

   public void setSex(String sex) {
       this.sex = sex;
   }

   public Integer getId() {
       return id;
   }

   public void setId(Integer id) {
       this.id = id;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public String getAge() {
       return age;
   }

   public void setAge(String age) {
       this.age = age;
   }
}


测试


public class test {
   public static void main(String[] args) throws Exception {
    List<User> list = new ArrayList<>();
    list.add(new User(1,"小明","12"));
    list.add(new User(2,"小李","13"));
    list.add(new User(3,"小张","14"));
       XSSFWorkbook sheets = ExcelUtil.exportExcel(list);
       FileOutputStream fileOutputStream = new FileOutputStream("D:/test.xlsx");
       sheets.write(fileOutputStream);
       fileOutputStream.flush();
       fileOutputStream.close();
       sheets.close();
   }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值