09Apache POI学习笔记

           Apache POI学习笔记

1 Poi介绍

1.1 poi简介

1.有Apache公司提供

2.Java编写的免费开源的跨平台的Java API

3.提供API给Java程序堆Microsoft Office格式档案读和写的功能

1.2 依赖包

<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>

1.3 POI包结构

​ 。HSSF – 读写Microsoft Excel XLS

​ 。XSSF --读写Microsoft Excel OOXML XLSX

​ 。HWPF–读写Microsoft Word DOC

​ 。HSLF --读写Microsoft PowerPoint

1.4 优劣势

Jxl:x消耗小,图片和图形支持有限

POI:功能更加完善,用户量的最大,使用最简单

2 入门案例

image-20211227142211287

2.1 从Excel文件读取数据

2.1.1 读取步骤

1.获取工作薄 workbook (Excel文件)

2.获取工作表 sheet

3.遍历工作表获得行对象 row

4.遍历行对象获取单元格对象 cell

5.获得单元格的值

H:\009Apache POI\hello.xlsx

image-20211227152240398

2.1.2 读取Excel

package com.tangguanlin.poi;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
/**
 * 说明:Poi读取Excel
 * 作者:汤观林
 * 日期:2021年12月27日 14时
 */
public class ReadExcel1 {
    public static void main(String[] args) throws IOException {

        //1.获取工作薄 workbook
        XSSFWorkbook workbook = new XSSFWorkbook("H:\\009Apache POI\\hello.xlsx");

        //2.获取工作表 sheet
        //XSSFSheet sheet = workbook.getSheetAt(0); //根据下标取
        XSSFSheet sheet = workbook.getSheet("Sheet1"); //根据名称取

        //普通for循环
        int lastRowNum = sheet.getLastRowNum();  //最大行数
        for(int i=0;i<=lastRowNum;i++){
            Row row = sheet.getRow(i);
            short lastCellNum = row.getLastCellNum(); //最大列数
            for(int j=0;j<lastCellNum;j++){
                String value = row.getCell(j).getStringCellValue();
                System.out.println(value);
            }
        }

        //增强for循环-------------------------------------------------------------
        //3.遍历工作表获得行对象 row
        for(Row row:sheet){
            //4.遍历行对象获取单元格对象 cell
             for(Cell cell:row){
                 //5.获得单元格的值
                 String content = cell.getStringCellValue();
                 System.out.println(content);
             }
        }

        //6.释放资源
       workbook.close();  
    }
}

运行结果:

你好
我的
世界

2.2 向Excel文件写入数据

2.2.1 写入步骤

1.创建一个Excel工作薄 workbook (Excel文件)

2.创建工作表 sheet

3.创建行 row

4.创建单元格赋值 cell

5.通过输出流将对象下载到磁盘

2.2.2 写入Excel

package com.tangguanlin.poi;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 说明:Poi写入Excel
 * 作者:汤观林
 * 日期:2021年12月27日 15时
 */
public class WriteExcel1 {
    public static void main(String[] args) throws IOException {

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

        //3.创建行
        XSSFRow row0 = sheet.createRow(0);
        //4.创建列
        row0.createCell(0).setCellValue("传智播客");
        row0.createCell(1).setCellValue("黑马程序员");
        row0.createCell(2).setCellValue("博学谷");

        XSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("传智播客");
        row1.createCell(1).setCellValue("黑马程序员");
        row1.createCell(2).setCellValue("博学谷");

        //5.输出流
        FileOutputStream out = new FileOutputStream("H:\\009Apache POI\\heima.xlsx"); //文件位置 不存在会自动创建
        workbook.write(out);
        out.flush();

        //6.释放资源
        out.close();
        workbook.close();
        System.out.println("写入成功");
    }
}

运行结果:

H:\009Apache POI\heima.xlsx

image-20211227155212163

3 实战练习

3.1 样式

3.1.1 对齐方式

 //创建单元格样式对象
XSSFCellStyle cellStyle = workbook.createCellStyle();

        //创建字体样式
        XSSFFont font = workbook.createFont();
        font.setFontName("黑体"); 	//字体
        font.setColor(IndexedColors.BLUE.getIndex()); 	//字体颜色
    cellStyle.setFont(font);

	cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  // 设置单元格水平方向对其方式
	cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置单元格垂直方向对其方式
	
//列中使用单元格样式
cell1.setCellStyle(cellStyle);

img

3.1.2 边框

//创建单元格样式对象
XSSFCellStyle cellStyle = workbook.createCellStyle();

    cellStyle.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); //上边边框          
    cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());  //上边边框颜色
	cellStyle.setBorderRight(CellStyle.BORDER_THIN); 	//右边边框                	
    cellStyle.setRightBorderColor(IndexedColors.BLUE.getIndex());  //右边边框颜色  
	cellStyle.setBorderBottom(CellStyle.BORDER_THIN); 	//底部边框
    cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //底部边框颜色         
    cellStyle.setBorderLeft(CellStyle.BORDER_THIN);  	//左边边框
    cellStyle.setLeftBorderColor(IndexedColors.RED.getIndex()); //左边边框颜色
        
//列中使用单元格样式         
cell.setCellStyle(cellStyle);

img

3.1.3 背景颜色

//创建单元格样式对象
XSSFCellStyle cellStyle = workbook.createCellStyle();


cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); //背景色
cellStyle.setFillPattern(CellStyle.BIG_SPOTS);
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); //前景色
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);  

//列中使用单元格样式         
cell.setCellStyle(cellStyle);

img

3.1.4 合并单元格

 //  									起始行  结束行  起始列   结束列
sheet.addMergedRegion(new CellRangeAddress(1,  	 2,		1, 	   2));                                         

img

3.2 导入Excel

H:\009Apache POI\product.xlsx

image-20211227194322883

代码:

Product产品类:

package com.tangguanlin.poi;
import lombok.Data;
/**
 * 说明:产品类
 * 作者:汤观林
 * 日期:2021年12月27日 16时
 */
@Data
public class Product {
    private  int pid;
    private String pname;
    private double price;
    private  int pstock;
}

Import导入类:

package com.tangguanlin.poi.web;
import com.tangguanlin.poi.model.Product;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 说明:导入Excel文件数据
 * 作者:汤观林
 * 日期:2021年12月27日 16时
 */
public class Import {
    public static void main(String[] args) throws IOException {

        //读取Excel文件中的数据
        List<Product> productList = new ArrayList<Product>();

         //1 获取工作薄workbook
        XSSFWorkbook workbook = new XSSFWorkbook("H:\\009Apache POI\\product.xlsx");
         //2 获取sheet
        XSSFSheet sheet = workbook.getSheetAt(0);
        //3 获取行
        int lastRowNum = sheet.getLastRowNum();  //最大行数
        for(int i=1;i<=lastRowNum;i++){
            XSSFRow row = sheet.getRow(i);
            if(row!=null){
                List<String> list = new ArrayList<>();
                for(Cell cell: row){
                    if(cell!=null){
                        cell.setCellType(Cell.CELL_TYPE_STRING); //统一设置为string类型
                        list.add(cell.getStringCellValue());
                    }
                }
                Product product = new Product(Integer.valueOf(list.get(0)),list.get(1),Double.valueOf(list.get(2)),Integer.valueOf(list.get(3)));
                productList.add(product);
            }
        }
        for(Product product:productList){
            System.out.println(product);
        }
    }
}

运行结果:

Product{pid=1, pname='苹果', price=25.0, pstock=100}
Product{pid=2, pname='皇冠梨', price=15.0, pstock=300}
Product{pid=3, pname='香蕉', price=18.0, pstock=250}
Product{pid=4, pname='火龙果', price=3.0, pstock=100}
Product{pid=5, pname='榴莲', price=5.0, pstock=50}
Product{pid=6, pname='橙子', price=2.0, pstock=120}

3.3 导出Excel

package com.tangguanlin.poi.web;
import com.tangguanlin.poi.model.Product;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * 说明:将数据导出到Excel
 * 作者:汤观林
 * 日期:2021年12月27日 16时
 */
public class Export {
    public static void main(String[] args) throws IOException {

        //将数据写入到Excel文件中
        List<Product> productList = new ArrayList<>();
        Product product1 = new Product(1,"苹果",25.0,100);
        productList.add(product1);
        Product product2 = new Product(1,"皇冠梨",15.0,300);
        productList.add(product2);
        Product product3 = new Product(1,"香蕉",18.0,250);
        productList.add(product3);
        Product product4 = new Product(1,"火龙果",3.0,100);
        productList.add(product4);
        Product product5 = new Product(1,"榴莲",5.0,50);
        productList.add(product5);
        Product product6 = new Product(1,"橙子",2.0,120);
        productList.add(product6);

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

        //创建单元格样式对象
        XSSFCellStyle cellStyle = workbook.createCellStyle();

        //对齐方式
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直居中

        //边框
        cellStyle.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); //上边边框
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());  //上边边框颜色
        cellStyle.setBorderRight(CellStyle.BORDER_THIN); 	//右边边框
        cellStyle.setRightBorderColor(IndexedColors.BLUE.getIndex());  //右边边框颜色
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN); 	//底部边框
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //底部边框颜色
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);  	//左边边框
        cellStyle.setLeftBorderColor(IndexedColors.RED.getIndex()); //左边边框颜色

        //背景颜色
        cellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex()); //前景色
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); //实心
        cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex()); //背景色
        cellStyle.setFillPattern(CellStyle.BIG_SPOTS);

            //创建字体样式
            XSSFFont font = workbook.createFont();
            font.setFontName("黑体"); //字体
            font.setColor(IndexedColors.BLUE.getIndex()); //字体颜色
        cellStyle.setFont(font);


        XSSFRow row0 = sheet.createRow(0);
            XSSFCell cell0 = row0.createCell(0);
            cell0.setCellValue("商品编号");
            cell0.setCellStyle(cellStyle);

            XSSFCell cell1 = row0.createCell(1);
            cell1.setCellValue("商品名称");
            cell1.setCellStyle(cellStyle);
            XSSFCell cell2 = row0.createCell(2);
            cell2.setCellValue("商品价格(单位:元/斤)");
            cell2.setCellStyle(cellStyle);
            XSSFCell cell3 = row0.createCell(3);
            cell3.setCellValue("商品库存(单位:吨)");
            cell3.setCellStyle(cellStyle);

        for(int i=0;i<productList.size();i++){
            //3.创建行
            XSSFRow row = sheet.createRow(i+1);
            //4.创建列
            row.createCell(0).setCellValue(productList.get(i).getPid());
            row.createCell(1).setCellValue(productList.get(i).getPname());
            row.createCell(2).setCellValue(productList.get(i).getPrice());
            row.createCell(3).setCellValue(productList.get(i).getPstock());
        }

        //合并单元格                           起始行 结束行 起始列 结束列
        sheet.addMergedRegion(new CellRangeAddress(3,5,1,3));

        //5.输出流
      FileOutputStream out = new FileOutputStream("H:\\009Apache POI\\product_export.xlsx"); //文件位置 不存在会自动创建
        workbook.write(out);
        out.flush(); //输出

        //6.释放资源
        out.close();
        workbook.close();
        System.out.println("写入成功");
    }
}

运行结果:

H:\009Apache POI\product_export.xlsx

image-20211227194219943

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值