• Java使用POI对Excel进行基本操作(2)-基本操作和样式设置


    1、使用poi创建工作簿和 sheet

        public static void main(String[] args) throws Exception {
            // 定义一个新的工作簿
            Workbook workbook = new XSSFWorkbook();
            // 创建一个新的sheet
            workbook.createSheet("test1");
            
            FileOutputStream fileOutputStream = new FileOutputStream("D:\用poi搞出来的工作簿.xlsx");
            // 写入到文件
            workbook.write(fileOutputStream);
            fileOutputStream.close();
        }

    2、使用poi创建单元格

        public static void main(String[] args) throws Exception {
            // 定义一个工作簿
            Workbook workbook = new XSSFWorkbook();
            // 创建一个sheet页
            Sheet sheet = workbook.createSheet("第一个sheet页");
            // 创建一个行
            Row row = sheet.createRow(0);
            // 创建单元格,赋值不同类型
            row.createCell(0).setCellValue(1);
            row.createCell(1).setCellValue(1.2);
            row.createCell(2).setCellValue("这是一个字符串类型的");
            row.createCell(3).setCellValue(false);
    
            FileOutputStream fileOutputStream = new FileOutputStream("D:\用poi搞出来的cell.xlsx");
            // 写入到文件
            workbook.write(fileOutputStream);
            fileOutputStream.close();
        }

    3、设置单元格样式

        public static void main(String[] args) throws Exception {
            // 定义一个工作簿
            Workbook workbook = new XSSFWorkbook();
            // 创建一个sheet页
            Sheet sheet = workbook.createSheet("第一个sheet页");
            // 创建一个行
            Row row = sheet.createRow(0);
            // 创建一个单元格,第1列
            Cell cell = row.createCell(0);
            cell.setCellValue("测试内容");
            // 设置边框
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setBorderTop(BorderStyle.DOUBLE);
            cell.setCellStyle(cellStyle);
    
            // 设置字体
            Font font = workbook.createFont();
            font.setFontName("华文行楷");
            font.setFontHeightInPoints((short)32);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
    
            // 设置对齐方式
            cellStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
            cell.setCellStyle(cellStyle);
    
            FileOutputStream fileOutputStream = new FileOutputStream("D:\用poi搞出来的cellstyle.xlsx");
            workbook.write(fileOutputStream);
            fileOutputStream.close();
        }
  • 相关阅读:
    tfrecord汇总
    python2中的编码的问题
    python multiprocessing的问题
    转载,ubuntu shell ~/.bashrc /etc/bash.bashrc
    singleton模式 Python
    目标检测 tensorflow(预训练模型)
    functools.partial 小记
    python 踩坑小计 virtualenv-site-packages
    python3.6 _tkinter module问题 python源码重新编译
    windows核心编程之网络编程入门篇
  • 原文地址:https://www.cnblogs.com/lkc9/p/12256220.html
Copyright © 2020-2023  润新知