• 【Java】导入/导出数据到excel表格


    在做这些之前你可能还需要导入相应的依赖

            <!-- ository.com/artifact/org.apache.poi/poi -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.17</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.17</version>
            </dependency>
    

    导出

    如果使用POI从Java中导出数据到excel表格只需要非常简单的步骤:

    1. 创建一个workbook
      我的理解就是新建一个工作空间,即excel文件。
    2. 创建一个sheet
      这个就是excel中的sheet
    3. 创建一个row
      顾名思义,一个新的列
    4. 创建一个cell
      每列中的单元格
    5. 往cell里面填充数据
    6. 重复3-5

    Demo

    奉上一个简单的Demo,注释里面写的很清楚,相信可以做到一看就懂。

    public class ExportDemo {
    
        private static final List<UserInformation> userInformationList = Arrays
                .asList(new UserInformation("张飞", "三哥@sg.com", 14),
                        new UserInformation("刘备", "大弟@sg.com", 28),
                        new UserInformation("关羽", "二哥@sg.com", 27));
    
        private static final String[] titles = {"序号", "用户名", "邮箱", "年龄"};
    
        public static void main(String[] args) {
    
            //创建一个workbook
            XSSFWorkbook workbook = new XSSFWorkbook();
            //创建一个sheet
            XSSFSheet sheet = workbook.createSheet("sheet");
            //创建一列
            XSSFRow row = null;
            //创建一个单元格
            XSSFCell cell = null;
    
            try {
                //设置标题
                row = sheet.createRow(0);
                for (int i = 0; i < titles.length; i++) {
                    //创建单元格
                    cell = row.createCell(i);
                    cell.setCellValue(titles[i]);
                }
    
                //设置内容
                for (int i = 0; i < userInformationList.size(); i++) {
                    //获取实例
                    UserInformation userInformation = userInformationList.get(i);
                    //设置序号
                    int index = i + 1;
                    row = sheet.createRow(index);
    
                    //将序号内容存入单元格
                    row.createCell(0).setCellValue(index);
                    //将用户名内容存入单元格
                    if (StringUtils.isNotBlank(userInformation.getUsername())) {
                        row.createCell(1).setCellValue(userInformation.getUsername());
                    }
                    //将邮箱内容存入单元格
                    if (StringUtils.isNotBlank(userInformation.getEmail())) {
                        row.createCell(2).setCellValue(userInformation.getEmail());
                    }
                    //将年龄内容存入单元格
                    if (null != userInformation.getAge()) {
                        row.createCell(3).setCellValue(userInformation.getAge());
                    }
    
                }
    
                FileOutputStream out = new FileOutputStream("h:\workbook.xls");
    
                try {
                    workbook.write(out);
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    

    结果:

    导入

    如果使用POI从excel表格中导入数据到java,道理同导出类似,只不过使用不同的api。

    Demo

     public static void main(String[] args) {
            String[][] dateStrings = new String[0][];
            try (FileInputStream fileInputStream = new FileInputStream("a.xls")) {
                dateStrings = importExcel(fileInputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(dateStrings);
        }
    
        private static String[][] importExcel(InputStream inputStream) throws IOException {
            // 获取 workbook
            Workbook workbook = new XSSFWorkbook(inputStream);
            // 获取 sheet
            Sheet sheet = workbook.getSheetAt(0);
            // 总行数
            int totalRows = sheet.getLastRowNum() + 1;
            // 总列数
            int totalColumn = sheet.getRow(0).getPhysicalNumberOfCells();
            // 二维String数组来存储数据
            String[][] tableData = new String[totalRows][totalColumn];
            for (int r = 0; r < totalRows; r++) {
                // 获得 行 row
                Row row = sheet.getRow(r);
                String[] rowData = new String[totalColumn];
                for (int c = 0; c < totalColumn; c++) {
                    // 获取 单元格 cell
                    Cell cell = row.getCell(c);
                    // 获取单元格元素类型
                    CellType type = cell.getCellTypeEnum();
                    String cellVal;
                    switch (type) {
                        case STRING:
                            cellVal = cell.getStringCellValue().trim();
                            break;
                        case NUMERIC:
                            double val = cell.getNumericCellValue();
                            cellVal = String.valueOf(val);
                            double valDiv = val % 1.0;
                            if (valDiv == 0) {
                                cellVal = String.valueOf((long) val);
                            }
                            break;
                        case BOOLEAN:
                            cellVal = String.valueOf(cell.getBooleanCellValue());
                            break;
                        default:
                            cellVal = "";
                            break;
                    }
                    rowData[c] = cellVal;
                }
                tableData[r] = rowData;
            }
            return tableData;
        }
    

    结果:

    工具类

    • 自定义

    市面上有很多开源的工具类,非常的方便,虽然不提倡反复的造轮子,但是再造轮子的过程中,可以让自己提升,下面的链接时笔者自己开发的一个工具类,非常简单,也做了很多注释。希望可以帮到大家。

    强大的开源Excel工具类

    • hutool

    hutool是非常强大的工具包,里面也有相应的工具类可以使用。

  • 相关阅读:
    简单多线程创建
    ajax 实现局部页面更新
    基础分页查询解题思路
    cookie实现登录时间记录
    servlet过滤器
    jstl标签 URL智能寻找路径
    taglib遍历foreach循环list集合
    python之内置高阶函数
    python之lambda的使用
    python中的函数
  • 原文地址:https://www.cnblogs.com/zllk/p/14006739.html
Copyright © 2020-2023  润新知