Java Poi 创建与读取Excel

简介: Poi 包下载创建实体Java Bean--Studentpublic class Student { private int id; private String name; private int age; ...
  1. Poi 包下载

  2. 创建实体Java Bean--Student


public class Student {
    private int id;
    private String name;
    private int age;
    private Date birth;
    
    public Student() {  }
    
    public Student(int id, String name, int age, Date birth) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.birth = birth;
    }

    public int getId() {
        return id;
    }

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

    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 Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }
        
}
  1. 创建Excel表

public class CreateXLS {
    private static String path = "E:/Student.xls";
    private static List<Student> mList;
    /**工作簿*/
    private static HSSFWorkbook workbook;

    static {
        mList = new ArrayList<Student>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
        try {
            Student user1 = new Student(1, "张三", 16,
                    dateFormat.parse("1997-03-12"));
            Student user2 = new Student(2, "李四", 17,
                    dateFormat.parse("1996-08-12"));
            Student user3 = new Student(3, "王五", 26,
                    dateFormat.parse("1985-11-12"));
            mList.add(user1);
            mList.add(user2);
            mList.add(user3);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        workbook = new HSSFWorkbook();
        // 第二步, 在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = workbook.createSheet("学生表一");
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);
        // 第四步,创建单元格,并设置值表头,设置表头居中
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
        // 创建第一行
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("学号");
        cell.setCellStyle(style);
        
        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);
        
        cell = row.createCell(2);
        cell.setCellValue("年龄");        
        cell.setCellStyle(style);
        
        cell = row.createCell(3);
        cell.setCellValue("生日");
        cell.setCellStyle(style);
        // 第五步,写入实体数据 实际应用中这些数据从数据库得到,
        for (int i = 0; i < mList.size(); i++) {
            row = sheet.createRow(i + 1);
            Student student = mList.get(i);
            // 第四步,创建单元格,并设置值
            row.createCell((short) 0).setCellValue((double) student.getId());
            row.createCell((short) 1).setCellValue(student.getName());
            row.createCell((short) 2).setCellValue((double) student.getAge());
            cell = row.createCell((short) 3);
            cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(student.getBirth()));
        }
        
        try{
            FileOutputStream fout = new FileOutputStream(path);
            workbook.write(fout);
            fout.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
  1. 读取Excel表

public class ReadXLS {
    private static String path = "E:/Student.xls";
    
    public static void main(String[] args) throws IOException {
        List<List<Map<String,String>>> list = readExcelWithTitle(path);
        System.out.println(list.toString());
    }
    
    /**
     * [[{姓名=张三, 生日=1997-03-12, 学号=1.0, 年龄=16.0}, 
     *   {姓名=李四, 生日=1996-08-12, 学号=2.0, 年龄=17.0}, 
     *   {姓名=王五, 生日=1985-11-12, 学号=3.0, 年龄=26.0}]]
     */
    public static List<List<Map<String, String>>> readExcelWithTitle(String path) throws IOException {
        String fileType = path.substring(path.lastIndexOf(".")+1, path.length());
        InputStream inputStream = null;
        Workbook workbook = null;
        try {
            inputStream = new FileInputStream(path);
            if (fileType.equals("xls")){
                workbook = new HSSFWorkbook(inputStream);
            }
            // 对应excel文件
            List<List<Map<String, String>>> result = new ArrayList<List<Map<String,String>>>();
            // 遍历sheet页
            int sheetSize = workbook.getNumberOfSheets();
            
            for (int i = 0; i < sheetSize; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                // 对应sheet页
                List<Map<String, String>> sheetList = new ArrayList<Map<String,String>>();
                // 对应所有标题
                List<String> titles = new ArrayList<String>();
                // 遍历行
                int rowSize = sheet.getLastRowNum() + 1;
                for (int j = 0; j < rowSize; j++) {
                    Row row = sheet.getRow(j);
                    if (null == row) { // 略过空行
                        continue;
                    }
                    
                    int cellSize = row.getLastCellNum();// 行中有多少个单元格,也就是有多少列
                    if (0 == j) {
                        for (int k = 0; k < cellSize; k++) {
                            Cell cell = row.getCell(k);
                            titles.add(cell.toString());
                        }
                    } else { // 其他数据行
                        Map<String, String> rowMap = new HashMap<String, String>();
                        for (int k = 0; k < cellSize; k++) {
                            Cell cell = row.getCell(k);
                            String key = titles.get(k);
                            String value = null;
                            if (null != cell) {
                                value = cell.toString();
                            }
                            rowMap.put(key, value);
                        }
                        sheetList.add(rowMap);
                    }
                }
                result.add(sheetList);              
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != workbook) {
                workbook.close();
            }
            if (null != inputStream) {
                inputStream.close();
            }
        }       
        return null;
    }
}
目录
相关文章
|
3月前
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
190 5
|
2月前
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
138 9
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
3月前
|
Java BI API
Java Excel报表生成:JXLS库的高效应用
在Java应用开发中,经常需要将数据导出到Excel文件中,以便于数据的分析和共享。JXLS库是一个强大的工具,它基于Apache POI,提供了一种简单而高效的方式来生成Excel报表。本文将详细介绍JXLS库的使用方法和技巧,帮助你快速掌握Java中的Excel导出功能。
96 6
|
3月前
|
Java API Apache
|
3月前
|
存储 Java API
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
Java实现导出多个excel表打包到zip文件中,供客户端另存为窗口下载
144 4
|
4月前
|
前端开发 JavaScript Java
导出excel的两个方式:前端vue+XLSX 导出excel,vue+后端POI 导出excel,并进行分析、比较
这篇文章介绍了使用前端Vue框架结合XLSX库和后端结合Apache POI库导出Excel文件的两种方法,并对比分析了它们的优缺点。
1410 0
|
5月前
|
存储 Java
java的Excel导出,数组与业务字典匹配并去掉最后一个逗号
java的Excel导出,数组与业务字典匹配并去掉最后一个逗号
76 2
|
4月前
|
Java Apache
Apache POI java对excel表格进行操作(读、写) 有代码!!!
文章提供了使用Apache POI库在Java中创建和读取Excel文件的详细代码示例,包括写入数据到Excel和从Excel读取数据的方法。
174 0
|
Java 数据处理 数据库
重构:以Java POI 导出EXCEL为例2
前言 上一篇博文已经将一些对象抽象成成员变量以及将一些代码块提炼成函数。这一节将会继续重构原有的代码,将一些函数抽象成类,增加成员变量,将传入的参数合成类等等。 上一篇博文地址:http://www.cnblogs.
1285 0
|
Java C# C++
重构:以Java POI 导出EXCEL为例
重构 开头先抛出几个问题吧,这几个问题也是《重构:改善既有代码的设计》这本书第2章的问题。 什么是重构? 为什么要重构? 什么时候要重构? 接下来就从这几个问题出发,通过这几个问题来系统的了解重构的意义。
1410 0