zoukankan      html  css  js  c++  java
  • 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();
        }
  • 相关阅读:
    Android Service
    Java 关键字 static final
    Django | mysql修改个别表后save()报错
    Django | Unable to get repr for <class 'django.db.models.query.QuerySet'>
    MySQL | linux中数据库导出和导入
    MySQL | 查看log日志
    python | log日志
    python | 网络编程(socket、udp、tcp)
    Python | 异常处理
    Python | 单例模式
  • 原文地址:https://www.cnblogs.com/lkc9/p/12256220.html
Copyright © 2011-2022 走看看