POI导出Excel:

来源:互联网 发布:deepin 安装软件 编辑:程序博客网 时间:2024/06/05 16:28

自己整理的POI导出Excel:

-

pox.xml 配置文件里面添加 poi:

这里使用的是POI3.16版本——POI

        <!-- POI -->            <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi</artifactId>            <version>3.16</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml</artifactId>            <version>3.16</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml-schemas</artifactId>            <version>3.16</version>        </dependency>        <!-- POI end -->

ExportExcel工具:

import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.lang.reflect.Field;import java.math.BigDecimal;import java.sql.Timestamp;import java.text.DecimalFormat;import java.text.NumberFormat;import java.text.SimpleDateFormat;import java.util.Collection;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import javax.swing.JOptionPane;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFDataFormat;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.HorizontalAlignment;public class ExportExcel<T> {    /**     * 这一段为测试代码;     * 测试实体类:(直接封装即可)     * public class Student {     *   private Integer id;     *   private String name;     *   private String sex;     */     public static void main(String[] args) {            // 声明一个工作薄        HSSFWorkbook wb = new HSSFWorkbook();        // 声明一个单子并命名        HSSFSheet sheet = wb.createSheet("学生表");        // 给单子名称一个长度        sheet.setDefaultColumnWidth((short) 15);        // 生成一个样式        HSSFCellStyle style = wb.createCellStyle();        // 创建第一行(也可以称为表头)        HSSFRow row = sheet.createRow(0);        // 样式字体居中        style.setAlignment(HorizontalAlignment.CENTER);        // 给表头第一行一次创建单元格        HSSFCell cell = row.createCell((short) 0);        cell.setCellValue("学生编号");        cell.setCellStyle(style);        cell = row.createCell((short) 1);        cell.setCellValue("学生姓名");        cell.setCellStyle(style);        cell = row.createCell((short) 2);        cell.setCellValue("学生性别");        cell.setCellStyle(style);        // 添加一些数据,这里先写死,大家可以换成自己的集合数据        List<Student> list = new ArrayList<Student>();        list.add(new Student(123, "123", "465"));        list.add(new Student(111, "李四", "男"));        list.add(new Student(111, "王五", "女"));        // 向单元格里填充数据        for (short i = 0; i < list.size(); i++) {            row = sheet.createRow(i + 1);            row.createCell(0).setCellValue(list.get(i).getId());            row.createCell(1).setCellValue(list.get(i).getName());            row.createCell(2).setCellValue(list.get(i).getSex());        }        try {            // 默认导出到E盘下            FileOutputStream out = new FileOutputStream("E://学生表.xls");            wb.write(out);            out.close();            JOptionPane.showMessageDialog(null, "导出成功!");        } catch (FileNotFoundException e) {            JOptionPane.showMessageDialog(null, "导出失败!");            e.printStackTrace();        } catch (IOException e) {            JOptionPane.showMessageDialog(null, "导出失败!");            e.printStackTrace();        }    }//测试结束;//************************    /**     *      * @param title     *            表格标题名     * @param headersName     *            表格属性列名数组     * @param headersId     *            表格属性列名对应的字段     * @param dataset     *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象     * @param out     *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中     */    public void exportExcel(String title, String[] headersName,            String[] headersId, List<T> dtoList) {        // 表头        Map<Integer, String> map = new HashMap<Integer, String>();        int key = 0;        for (int i = 0; i < headersName.length; i++) {            if (!headersName[i].equals(null)) {                map.put(key, headersName[i]);                key++;            }        }        // 字段        Map<Integer, String> zdMap = new HashMap<Integer, String>();        int value = 0;        for (int i = 0; i < headersId.length; i++) {            if (!headersId[i].equals(null)) {                zdMap.put(value, headersId[i]);                value++;            }        }        // 声明一个工作薄        HSSFWorkbook wb = new HSSFWorkbook();        HSSFSheet sheet = wb.createSheet(title);        sheet.setDefaultColumnWidth((short) 15);        // 生成一个样式        HSSFCellStyle style = wb.createCellStyle();        HSSFRow row = sheet.createRow(0);        style.setAlignment(HorizontalAlignment.CENTER);        HSSFCell cell;        Collection c = map.values();        Iterator<String> it = c.iterator();        // 根据选择的字段生成表头        short size = 0;        while (it.hasNext()) {            cell = row.createCell(size);            cell.setCellValue(it.next().toString());            cell.setCellStyle(style);            size++;        }        // 字段        Collection zdC = zdMap.values();        Iterator<T> labIt = dtoList.iterator();        int zdRow = 0;        while (labIt.hasNext()) {            // int zdCell = 0;            zdRow++;            row = sheet.createRow(zdRow);            T l = (T) labIt.next();            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值            Field[] fields = l.getClass().getDeclaredFields();            for (short i = 0; i < fields.length; i++) {                Field field = fields[i];                field.setAccessible(true);                // String fieldName = field.getName();                Object val;                try {                    val = field.get(l);                    // System.out.println(val);                    String type = field.getType().toString();// 得到此属性的类型                    // System.out.println(type);                    if (type.endsWith("String")) {                        row.createCell(i).setCellValue((String) val);                    } else if (type.endsWith("int") || type.endsWith("Integer")) {                        row.createCell(i).setCellValue((double) val);                    } else if (type.endsWith("Boolean")) {                        row.createCell(i).setCellValue((boolean) val);                    } else if (type.endsWith("Date")) {                        // 如果是日期格式,设置单元格格式;                        HSSFCell cella = row.createCell(i);                        cella.setCellValue((Date) val);                        HSSFCellStyle cellStyle = wb.createCellStyle();                        HSSFDataFormat format = wb.createDataFormat();                        cellStyle.setDataFormat(format.getFormat("yyyy-MM-dd"));                        cella.setCellStyle(cellStyle);                    } else if (type.endsWith("Timestamp")) {                        // 如果是日期格式,设置单元格格式;                        HSSFCell cella = row.createCell(i);                        cella.setCellValue((Date) val);                        HSSFCellStyle cellStyle = wb.createCellStyle();                        HSSFDataFormat format = wb.createDataFormat();                        cellStyle.setDataFormat(format                                .getFormat("yyyy-MM-dd HH:mm"));                        cella.setCellStyle(cellStyle);                    } else if (type.endsWith("BigDecimal")) {                        row.createCell(i).setCellValue((double) val);                    }                } catch (IllegalArgumentException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                } catch (IllegalAccessException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }        try {            FileOutputStream xls = new FileOutputStream("E://学生表AB.xls");            wb.write(xls);            xls.close();            // JOptionPane.showMessageDialog(null, "导出成功!");        } catch (FileNotFoundException e) {            // JOptionPane.showMessageDialog(null, "导出失败!");            e.printStackTrace();        } catch (IOException e) {            // JOptionPane.showMessageDialog(null, "导出失败!");            e.printStackTrace();        }    }}

控制器Controller:

    /**     *      * @return     */    @RequestMapping("/outexcel")    public String outall() {        String title = "表名称";        //列名称:        String[] headersName = { "一", "二", "三", "四", "五", "六", "七", "八", "九",                "十", "十一", "十二" };        //对应实体名(顺序一致);              String[] headersId = { "StoreLevelId", "SingleStoresLevel", "isShow",                "SlState", "StoreLevelItemId", "LevelItemName", "FieldType",                "OrderValue", "BusinessExplain", "SliState" };        //数据集合        List<StoreLevelResult> dtoList = sLevelServices.getLevelResults();        excel.exportExcel(title, headersName, headersId, dtoList);        //重定向        return "redirect:***";    }

测试效果

这里写图片描述
*
*
*

笔记;
我是一个新手;正在慢慢充实自己;
文章内容转载自:
Java利用POI实现数据的Excel导出

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 学车每次考不过怎么办 年检超期3个月怎么办 年检超过3个月怎么办 工商执照年检时候忘记密码怎么办 个体工商营业执照年检过期怎么办 忘了审车时间怎么办 汽车年检超过时间了怎么办 星巴克金星会员到期怎么办 驾考学员证丢了怎么办 违章扣满12分怎么办 违章扣满12分后怎么办 东方时尚驾校科二考不过怎么办 东方时尚科二科三考五次没过怎么办 不想考科目三了怎么办 科目三两次没过怎么办 练科目三很紧张怎么办 驾照学员卡丢了怎么办 驾考时考试的车系统出错怎么办 驾驶证超期6个月怎么办 北京汽车年检只有电子保单怎么办 交电费户号9位数怎么办 扬州驾照12分扣完了怎么办 有大专毕业证在深圳怎么办居住证 微信解释包错误怎么办 富士康离职不批怎么办 到了怀孕年龄找不到工作怎么办 建筑公司挂靠发生人员伤残怎么办 外地生小孩落北京户口怎么办 户籍档案查不到直系亲属关系怎么办 考过了二建注册怎么办 异地工作辞职回家档案怎么办 离职怎么办档案放在人才市场 人才房住了6年后怎么办 医保辞职后断了怎么办 社保断了生育险怎么办 深圳小产权房水电费纠纷怎么办 有公租房的再婚怎么办 廉租房被没收了怎么办 商铺到期房东不续租怎么办 天津集体户口买不起房怎么办 房东不想续租了怎么办