温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java如何使用POI操作Excel

发布时间:2022-02-28 11:28:14 来源:亿速云 阅读:272 作者:小新 栏目:web开发

这篇文章主要介绍了Java如何使用POI操作Excel,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

Java使用POI操作Excel

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文件内容

Java如何使用POI操作Excel

1.2.2. 代码

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

            String past = "/操作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());
                            }
                        }
                        //&hellip;&hellip;
                        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, 0, 3); // 起始行, 终止行, 起始列, 终止列
        sheet1.addMergedRegion(cra);
        //设置合并单元格的样式
        // 使用RegionUtil类为合并后的单元格添加边框
        // 下边框
        RegionUtil.setBorderBottom(BorderStyle.MEDIUM_DASHED, cra, sheet1);
        // 左边框
        RegionUtil.setBorderLeft(BorderStyle.MEDIUM_DASHED, cra, 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, 0, 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("/创建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文件内容

Java如何使用POI操作Excel
Java如何使用POI操作Excel

感谢你能够认真阅读完这篇文章,希望小编分享的“Java如何使用POI操作Excel”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI