org.apache.poi实现Excel的读取和导出

了解下poi包

在这里插入图片描述

第一步 创建一个maven项目,导poi包

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

了解下poi包中对象对应Excel表的中位置

在这里插入图片描述

第二步 实现对Excel文件的读取和写入

一.从Excel文件中读取数据

读取步骤:

1.创建工作薄
2.获取工作表
3.遍历工作表获取 行对象
4.遍历行对象获取 单元格对象
5.获取单元格中的值
6.释放资源

代码实现读取Excel

 //1.获取工作薄 (这里文件的路径用的是绝对路径)
XSSFWorkbook workbook = new XSSFWorkbook("/Users/xxx/Desktop/code/excel1.xlsx");

//2。获取工作表
XSSFSheet sheet = workbook.getSheetAt(0);

//3.获取行 
for (Row row : sheet) {
    //4.获取单元格
    for (Cell cell : row) {
    	//5.获取单元格中的值
        String stringCellValue = cell.getStringCellValue();
        //打印输出
        System.out.println(stringCellValue);
    }
}
//6.释放资源
 workbook.close();

//上述代码的 步骤3,4,5 也可以用使用索引的方式来获取单元格的值
// 替换步骤3,4,5 的代码
// 获取行数
int lastRowNum = sheet.getLastRowNum();
//循环遍历
for (int i = 0; i <= lastRowNum; i++) {
    //获取第(i+1)行
    XSSFRow row = sheet.getRow(i);
    if (row != null) {
        //获取本行有多少个单元格
        int cellNum = (int) row.getLastCellNum();
        //循环遍历
        for (int j = 0; j <= cellNum; j++) {
            // 获取第j+1个单元格
            XSSFCell cell = row.getCell(j);
            if (cell != null) {
                //获取单元格的内容,转成字符串
                String stringCellValue = cell.getStringCellValue();
                //打印输出
                System.out.println(stringCellValue);
            }
        }
    }
}

针对这样的Excel表格:
在这里插入图片描述
上述代码打印输出:

你好
我的
世界

Process finished with exit code 0

二.向Excel文件中写入数据

写入步骤

1.创建一个Excel文件
2.创建工作表
3.创建行
4.创建单元格 并赋值
5.通过输出流将对象下载到本地磁盘
6.释放资源

代码实现写入Excel

//1.创建工作博
  XSSFWorkbook workbook = new XSSFWorkbook();

  //2。创建工作表
  XSSFSheet sheet = workbook.createSheet("工作表1");

  //3。创建行
  //第一行
  XSSFRow row = sheet.createRow(0);
  //4。创建单元格,并赋值
  XSSFCell cell = row.createCell(0);
  cell.setCellValue("张三");
  row.createCell(1).setCellValue("李四");
  row.createCell(2).setCellValue("王二");
  row.createCell(3).setCellValue("麻子");

  //第二行
  XSSFRow row2 = sheet.createRow(1);
  row2.createCell(0).setCellValue("老大");
  row2.createCell(1).setCellValue("老二");
  row2.createCell(2).setCellValue("老三");
  row2.createCell(2).setCellValue("老四");
  //5.输出流 输出
  FileOutputStream fos = new FileOutputStream("/Users/xxx/Desktop/code/excel2.xlsx");
  //按照路径 输出excel表
  workbook.write(fos);

  //6.刷新流,释放资源
  fos.flush();
  fos.close();
  //关闭资源
  workbook.close();

输出效果图

在这里插入图片描述

加强练习(集合导出Excel表,读取Excel表封装成集合)

要读取的Excel表内容

在这里插入图片描述

代码实现读取Excel文件,输出集合

//1.创建工作薄
     XSSFWorkbook workbook = new XSSFWorkbook("/Users/xxx/Desktop/code/excelDemo.xlsx");
     //2.获取工作表
     XSSFSheet sheet = workbook.getSheetAt(0);
     //Fruit对应表头的类对象
     List<Fruit> list = new ArrayList<>();
     //3.解析excel表
     //第一行表头数据不要
     int rowNum = sheet.getLastRowNum();
     for (int i = 1; i <= rowNum; i++) {
         XSSFRow row = sheet.getRow(i);
         if (row != null) {
             Fruit fruit = new Fruit();

             XSSFCell cell0 = row.getCell(0);  //编号
             XSSFCell cell1 = row.getCell(1);  //水果名
             XSSFCell cell2 = row.getCell(2);  //水果价格
             XSSFCell cell3 = row.getCell(3);  //水果库存

             Double cellValue = cell0.getNumericCellValue();
             fruit.setId(cellValue.intValue());
             fruit.setName(cell1.getStringCellValue());
             fruit.setPrice(cell2.getNumericCellValue());

             Double cellValue1 = cell3.getNumericCellValue();
             fruit.setInventory(cellValue1.intValue());

             list.add(fruit);
         }
     }
     //4.释放资源
     workbook.close();
     //5.打印输出
System.out.println("list:" + list);
//输出内容
/*
list:
[Fruit:{id=1, name='苹果', price=2.3, inventory=100}, 
Fruit:{id=2, name='皇冠梨', price=3.4, inventory=200}, 
Fruit:{id=3, name='香蕉', price=3.5, inventory=234}, 
Fruit:{id=4, name='火龙果', price=5.6, inventory=123}, 
Fruit:{id=5, name='榴莲', price=35.6, inventory=12}, 
Fruit:{id=6, name='橙子', price=5.6, inventory=30}]

*/
//Fruit对应表头的类对象
//get,set,toString方法自己生成哈
public class Fruit {
    private Integer id;
    private String name;
    private double price;
    private Integer inventory;
}

// 上述代码的步骤 3替换下面代码
int lastRowNum = sheet.getLastRowNum();
 //第一行数据(表头) 不要
 for (int i = 1; i <= lastRowNum; i++) {
     XSSFRow row = sheet.getRow(i);
     //避免空指针
     if (row != null) {
         Fruit fruit = new Fruit();
         /*List<String> cellList = new ArrayList<>();
         for (Cell cell : row) {
             if (cell != null) {
                 //避免  数据类型转换异常
                 cell.setCellType(Cell.CELL_TYPE_STRING);
                 String cellValue = cell.getStringCellValue();
                 cellList.add(cellValue);
             }
         }
         if (cellList.size() > 0) {
             fruit.setId(Integer.parseInt(cellList.get(0)));
             fruit.setName(cellList.get(1));
             fruit.setPrice(Double.valueOf(cellList.get(2)));
             fruit.setInventory(Integer.parseInt(cellList.get(3)));
         }*/

         //第二种方法  使用索引
         int cellNum = row.getLastCellNum();
         for (int j = 0; j <= cellNum; j++) {
             XSSFCell cell = row.getCell(j);

             if (cell != null) {
                 cell.setCellType(Cell.CELL_TYPE_STRING);
                 if (j == 0) {
                     fruit.setId(Integer.parseInt(cell.getStringCellValue()));
                 } else if (j == 1) {
                     fruit.setName(cell.getStringCellValue());
                 } else if (j == 2) {
                     fruit.setPrice(Double.valueOf(cell.getStringCellValue()));
                 } else {
                     fruit.setInventory(Integer.parseInt(cell.getStringCellValue()));
                 }
             }

         }
         list.add(fruit);
     }
 }

代码根据集合,导出Excel文件

//1.创建工作薄
 XSSFWorkbook workbook = new XSSFWorkbook();
 //2.创建工作表
 XSSFSheet sheet = workbook.createSheet("工作表1");

 XSSFCellStyle style = workbook.createCellStyle();
 // 背景色: 浅黄色
 style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
 // 背景色填充样式:单色填充
 style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
 //水平居中
 style.setAlignment(HorizontalAlignment.CENTER);
 //垂直居中
 style.setVerticalAlignment(VerticalAlignment.CENTER);
 //3.创建行
 //首先创建第一行
 XSSFRow row = sheet.createRow(0);
 //创建第一行的单元格
 XSSFCell rowCell0 = row.createCell(0);
 rowCell0.setCellStyle(style);
 rowCell0.setCellValue("编号");
 XSSFCell rowCell1 = row.createCell(1);
 rowCell1.setCellStyle(style);
 rowCell1.setCellValue("水果名称");

 XSSFCell rowCell2 = row.createCell(2);
 rowCell2.setCellStyle(style);
 rowCell2.setCellValue("价格");

 XSSFCell rowCell3 = row.createCell(3);
 rowCell3.setCellStyle(style);
 rowCell3.setCellValue("库存");


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

 // 然后遍历水果集合,写数据到excel表上

 for (int i = 0; i < list.size(); i++) {
     //获取水果信息
     Fruit fruit = list.get(i);
     //创建excel的行,由于第一行已经创建过,所以这里从 索引为i+1的开始
     XSSFRow sheetRow = sheet.createRow(i + 1);

     //创建单元格,赋值
     //第一种方式
/*          XSSFCell cell0 = sheetRow.createCell(0);
     cell0.setCellValue(fruit.getId().toString());
     cell0.setCellStyle(cellStyle);

     XSSFCell cell1 = sheetRow.createCell(1);
     cell1.setCellValue(fruit.getName());
     cell1.setCellStyle(cellStyle);

     XSSFCell cell2 = sheetRow.createCell(2);
     cell2.setCellValue(String.valueOf(fruit.getPrice()));
     cell2.setCellStyle(cellStyle);

     XSSFCell cell3 = sheetRow.createCell(3);
     cell3.setCellValue(fruit.getInventory().toString());
     cell3.setCellStyle(cellStyle);*/

     //第二种方式
     for (int g = 0; g < 4; g++) {
         XSSFCell cell = sheetRow.createCell(g);
         cell.setCellStyle(cellStyle);
         if (g == 0) {
             cell.setCellValue(fruit.getId().toString());
         } else if (g == 1) {
             cell.setCellValue(fruit.getName());
         }else if (g==2){
             cell.setCellValue(String.valueOf(fruit.getPrice()));
         }else{
             cell.setCellValue(fruit.getInventory().toString());
         }
     }
 }

 FileOutputStream out = new FileOutputStream("/Users/xxxx/Desktop/code/excelWriteDemo6.xlsx");
 workbook.write(out);

 //刷新释放资源
 out.flush();
 out.close();
 workbook.close();

导出Excel文件内容和格式

在这里插入图片描述

单元格样式设计

//1.创建工作薄
 XSSFWorkbook workbook = new XSSFWorkbook();
 //2.创建工作表
 XSSFSheet sheet = workbook.createSheet("工作表1");
 //3.创建单元格样式
 XSSFCellStyle style = workbook.createCellStyle();

//填充背景色
// 背景色: 浅黄色
cellStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex()); 
// 背景色填充样式:单色填充
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); 

//设置样式布局
// 水平布局:居中
cellStyle.setAlignment(HorizontalAlignment.CENTER); 
// 垂直布局:居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

//设置边框
// 上薄边框
cellStyle.setBorderTop(BorderStyle.THIN);
// 下厚边框
cellStyle.setBorderBottom(BorderStyle.DOUBLE); 
// 左薄边框
cellStyle.setBorderLeft(BorderStyle.THIN);
// 右厚边框
cellStyle.setBorderRight(BorderStyle.DOUBLE); 
// 下边框:白色
cellStyle.setBottomBorderColor(IndexedColors.WHITE.getIndex()); 
// 右边框:绿色
cellStyle.setRightBorderColor(IndexedColors.GREEN.getIndex()); 

// 文本自动换行
cellStyle.setWrapText(true); 

//设置字体颜色,样式,关键代码:font.setColor(IndexedColors.BLACK.getIndex());
Font font = workbook.createFont();
// 加粗
font.setBold(false); 
// 字体
font.setFontName("微软雅黑"); 
// 字体高度
font.setFontHeightInPoints((short) 14); 
// 字体颜色:黑色
font.setColor(IndexedColors.BLACK.getIndex());
cellStyle.setFont(font);
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
org.apache.poi和easyexcel都是处理Excel文件的Java库。 org.apache.poi是一个流行的开源库,用于读取,创建和编辑Microsoft Office格式的文件,包括Excel文件。它提供了丰富的API来操作Excel文件,并且是一个强大而灵活的工具。使用org.apache.poi,你可以读取和写入Excel文件中的数据,操作单元格,样式,图表等等。 easyexcel是阿里巴巴开源的一个基于POI封装的Java库,专门用于处理Excel文件。它提供了简单易用的API,并且具有高效处理大数据量的能力。easyexcel可以读取和写入Excel文件,支持多种数据对象绑定和Excel模板导出功能。你可以使用easyexcel来快速处理和操作Excel文件,无论是读取大量的数据还是写入大型Excel文件。 这两个库都有各自的特点和优势,选择使用哪个库取决于你的具体需求和偏好。如果你需要更高级的功能和更大的灵活性,可以选择使用org.apache.poi。如果你更注重简单易用和高效处理大数据量的能力,可以选择使用easyexcel。无论你选择哪个库,都可以在你的Java应用程序中轻松地处理Excel文件。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [POI & EasyExcel.md](https://download.csdn.net/download/Lay_wei/12710354)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Apache POI 和 easyExcel](https://blog.csdn.net/qq_45929882/article/details/125587221)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Apache POI与easyExcel](https://blog.csdn.net/weixin_44718865/article/details/114771224)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值