JAVA POI做导出Excel功能

maven依赖 我这里版本是 3.9
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>
ExportExcelUtil.java
package com.mms.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExportExcelUtil<T> {
    public void export(String sheetName,String[] headers, String[] columns,List<T> lists, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
        sheet.setDefaultColumnWidth(15);
        HSSFCellStyle style = wb.createCellStyle();

        HSSFRow row = sheet.createRow(0);
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        for (int i = 0; i < headers.length; i++) {
            HSSFCell headerCell = row.createCell(i);
            headerCell.setCellValue(headers[i]);
            headerCell.setCellStyle(style);
        }

        Iterator<T> it = lists.iterator();
        int rowIndex = 0;
        while (it.hasNext()) {
            rowIndex++;
            row = sheet.createRow(rowIndex);
            T t = it.next();
            Field[] fields = t.getClass()
                    .getDeclaredFields();

            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String fieldName = field.getName();

                for (int j = 0; j < columns.length; j++) {
                    if (fieldName.equals(columns[j])) {
                        String getMethodName = "get" +
                                fieldName.substring(0, 1).
                                        toUpperCase() + fieldName.
                                substring(1);
                        Class cls = t.getClass();

                        Method getMethod = cls.getMethod(
                                getMethodName, new Class[] {});
                        Object val = getMethod.invoke(t, new Object[] {});
                        String textVal = null;
                        if (null != val) {
                            textVal = val.toString();
                        } else {
                            textVal = null;
                        }
                        row.createCell(j).
                                setCellValue(textVal);
                    }
                }
            }
        }

        try {
            //默认导出到E盘下
        String filename = sheetName + ".xls";
        FileOutputStream out = new FileOutputStream("E://"+filename);
        wb.write(out);
        out.close();
        JOptionPane.showMessageDialog(null, "导出成功!");
        } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "导出失败!");
        e.printStackTrace();
        }

           /* String filename = sheetName + ".xls";
            String filepath = request.getRealPath("/") + filename;
            FileOutputStream out = new FileOutputStream(filepath);
            wb.write(out);
            out.close();
            downloadExcel(filepath, response);*/
        }


        /**
         * 下载
         */
        public static void downloadExcel(String filepath, HttpServletResponse response)throws IOException {
        File file = new File(filepath);
        String fileName = file.getName();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
        response.setCharacterEncoding("utf-8");
        InputStream fis = new BufferedInputStream(new FileInputStream(file));
        byte[] b = new byte[fis.available()];
        fis.read(b);
        response.getOutputStream().write(b);
        fis.close();
    }
    }
Test.java
public static void exportUser() throws Exception {
        String sheetName = "student";   //导出的Excel名称
        String[] headers = {"姓名", "年龄", "年级"};
        String[] columns = {"name", "age", "grade"};
        //添加一些数据,大家可以从数据库里读取
        //为了方便这里先写死,


        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student("小白", 8, "二年级");
        Student student2 = new Student("小丽", 9, "三年级");
        Student student3 = new Student("小可爱", 10, "四年级");
        list.add(student1);
        list.add(student2);
        list.add(student3);


        ExportExcelUtil<Student> util = new ExportExcelUtil<Student>();

  util.export(sheetName, headers, columns, list);

  }

package com.mms.utils;

public class Student {
    private String name;
    private int age;
    private String grade;

    public Student() {
    }

    public Student(String name, int age, String grade) {
        super();
        this.name = name;
        this.age = age;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", grade=" + grade
                + "]";
    }
}


如需自由导出数据

例:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值