加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java使用POI操作Excel

发布时间:2020-12-15 07:30:40 所属栏目:Java 来源:网络整理
导读:1. POI操作Excel 1.1. 依赖 !--操作excel-- dependency groupIdorg.apache.poi/groupId artifactIdpoi/artifactId version4.1.0/version /dependency dependency groupIdorg.apache.poi/groupId artifactIdpoi-ooxml/artifactId version4.1.0/version /depen

1. POI操作Excel

1.1. 依赖

<!--操作excel-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.0</version>
        </dependency>

1.2. 读取Excel

1.2.1. Excel文件内容

1.2.2. 代码

/**
     * 读取excel
     */
    public static void readExcel() {
        InputStream inputStream = null;
        XSSFWorkbook xssfWorkbook = null;
        try {

            String past = "G:ProjectMyProjectsjavaSpringBootDemosrcmainjavacomoneprcdemodemo/操作excel.xlsx";
            inputStream = new FileInputStream(past);
            xssfWorkbook = new XSSFWorkbook(inputStream);
            //获取sheet的个数
            int numberOfSheets = xssfWorkbook.getNumberOfSheets();
            //获取指定的sheet
            System.out.println(numberOfSheets);

            //通过指定名称获取
            XSSFSheet sheet = xssfWorkbook.getSheet("笔记本");
            //通过下标获取
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(1);
            if (sheetAt != null) {
                //最后一行有数据的
                int lastRowNum = sheetAt.getLastRowNum();
                XSSFRow row;
                short lastCellNum;
                XSSFCell cell;

                for (int i = 0; i <= lastRowNum; i++) {
                    //获取指定行
                    row = sheetAt.getRow(i);
                    if (row == null) {
                        continue;
                    }
                    //最后一列有数据的
                    lastCellNum = row.getLastCellNum();
                    for (int j = 0; j <= lastCellNum; j++) {
                        cell = row.getCell(j);
                        if (cell == null) {
                            continue;
                        }
                        //数据类型
                        CellType cellType = cell.getCellType();
                        //字符串
                        if (CellType.STRING == cellType) {
                            System.out.println(cell.toString());
                        }
                        //数字
                        else if (CellType.NUMERIC == cellType) {
                            try {
                                System.out.println(cell.getDateCellValue());
                            } catch (Exception e) {
                                System.out.println(cell.toString());
                            }
                        }
                        //……
                        else {
                            System.out.println(cell.toString());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

1.2.3. 控制台输出结果

2
便签名称
便签分类
创建时间
创建人
拥有人
小明的便签
学习便签
Tue Sep 03 00:00:00 CST 2019
小明
小明
小明的个人便签
个人便签
Sun Sep 08 00:00:00 CST 2019
小明
小明

1.3. 生成excel

1.3.1. 代码

/**
     * 生成excel
     */
    public static void creatExcel() {
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();

        //创建一个sheet
        XSSFSheet sheet1 = xssfWorkbook.createSheet("第一个新建的sheet");

        //设置高度和宽度,也可以每行每列单独分开设置
        //参数为字符个数
        sheet1.setDefaultColumnWidth(20);
        sheet1.setDefaultRowHeight((short) (33 * 20));
        //第二个参数为字符宽度的1/256
        sheet1.setColumnWidth(5,30 * 256);

        //设置单元格样式
        XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();

        // 字体样式
        Font fontStyle = xssfWorkbook.createFont();
        fontStyle.setBold(true);
        // 字体
        fontStyle.setFontName("等线");
        // 大小
        fontStyle.setFontHeightInPoints((short) 11);
        // 将字体样式添加到单元格样式中
        cellStyle.setFont(fontStyle);

        //水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        //设置 单元格填充色
        DefaultIndexedColorMap defaultIndexedColorMap = new DefaultIndexedColorMap();
        XSSFColor clr = new XSSFColor(defaultIndexedColorMap);
        byte[] bytes = {
                (byte) 217,(byte) 217,(byte) 217
        };
        clr.setRGB(bytes);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(clr);

        //设置单元格不为锁定,可编辑,反是用了这个样式的都可编辑
        cellStyle.setLocked(false);
        //锁定整个sheet不可编辑
        sheet1.protectSheet("1231312");


        //创建一行数据
        XSSFRow row;
        XSSFCell cell;
        row = sheet1.createRow(0);
        cell = row.createCell(0);
        //设值
        cell.setCellValue("2");


        //合并单元格
        CellRangeAddress cra = new CellRangeAddress(1,1,3); // 起始行,终止行,起始列,终止列
        sheet1.addMergedRegion(cra);
        //设置合并单元格的样式
        // 使用RegionUtil类为合并后的单元格添加边框
        // 下边框
        RegionUtil.setBorderBottom(BorderStyle.MEDIUM_DASHED,cra,sheet1);
        // 左边框
        RegionUtil.setBorderLeft(BorderStyle.MEDIUM_DASHED,sheet1);
        row = sheet1.getRow(1);

        //设置合并单元格内的文本样式
        //但这个单元格的边框样式会覆盖上面设置的合并单元格的样式
        CellUtil.getCell(row,0).setCellStyle(cellStyle);


        //设置单个单元格的样式
        row = sheet1.createRow(2);
        cell = row.createCell(0);
        cell.setCellStyle(cellStyle);

        //设置数据校验
        //序列校验
        String[] strArray = {
                "星期一","星期二","星期三"
        };
        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet) sheet1);
        XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(strArray);
        CellRangeAddressList addressList = new CellRangeAddressList(3,3,2);
        XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint,addressList);
        //显示报错提示框
        validation.setShowErrorBox(true);
        validation.createErrorBox("错误提示","只能选择指定的内容!");
        //设置单元格右侧显示剪头符号,显示可用的选项,默认为true
        validation.setSuppressDropDownArrow(true);
        //显示提示信息
        validation.setShowPromptBox(true);
        validation.createPromptBox("提示信息","请选择星期填入!");
        sheet1.addValidationData(validation);

        //保护工作薄不可被修改
        xssfWorkbook.lockStructure();
        //这个不知道有啥用
        xssfWorkbook.lockRevision();
        //锁定excel的窗口大小,不能无限制的横向,纵向拉伸。
        xssfWorkbook.lockWindows();

        xssfWorkbook.createSheet("第二个人sheet");


        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream("G:ProjectMyProjectsjavaSpringBootDemosrcmainjavacomoneprcdemodemo创建excel.xlsx");
            xssfWorkbook.write(outputStream);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

1.3.2. 生成excel文件内容


1.4. 参考

https://www.cnblogs.com/gavincoder/p/9051803.html

https://blog.csdn.net/sxdtwym/article/details/54379592

https://blog.csdn.net/lipinganq/article/details/78090553

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读