Java poi学习个人整理笔记--Excel文件相关操作

poi中HSSF包常用API类说明


HSSFWorkbook Excel的文档对象

一、poi如何生成excel表

sheet表示excel中每一个表单; row表示1,2,3,4…每一行; cell表示每一行具体(ABCDE…)哪一个单元格
在这里插入图片描述
从Excel文件读取数据步骤:

  1. 创建工作簿(XSSFWorkbook)
  2. 获取工作表(XSSFSheet)
  3. 遍历工作表获得行对象
  4. 遍历行对象(row)获取单元格对象(cell)
  5. 获得单元格中的值

二、入门案例

1.导入依赖

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

2.读取excel表中的数据

基础版excel表内容如下:
[外链图片转存失败,源站可能有防盗在这里插入!链机制,建描述]议将图片上https://传(imblo-sdnimg.cn/20210114151929clz3769.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzczEyM3lx,size_16,color_FFFFFF,t_70)e)]

基础版:

public static void main(String[] args)throws IOException{
	//1.获取工作簿
	XSSFWorkbook wb=new XSSFWorkbook("E:\\poitest\\hello.xlsx");
	//2.获取工作表
	XSSFSheet sheet=wb.getSheetAt(0);
	//3.获取行
	for(Row row:sheet){
		//4.获取单元格
		for(Cell cell:row)	{
		//获取单元格中的内容
			String value=cell.getStringCellValue(); //针对只有String数据的
			System.out.println(value);
		}
	}
	//释放资源
	wb.close();
}

进阶版:

public List<List<Object>> readExcelData(InputStream in, String filename) throws Exception {
        List<List<Object>> list;

        //创建Excel工作薄
        Workbook work = getWorkbook(in, filename);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);   //获取行
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y); //获取单元格
                    //通过getCellValue方法获取当前行每一列中的数据
                    li.add(getCellValue(cell));
                }
                //将每一行的数据添加到list
                list.add(li);
            }
        }
        //释放资源
        in.close();
        return list;
    }

3.向excel文件写入数据

从Excel文件写入数据步骤:

  1. 创建一个Excel文件(XSSFWorkbook)
  2. 创建工作表(XSSFSheet)
  3. 创建行
  4. 创建单元格赋值
  5. 通过输出流将对象下载到磁盘
	    public static void main(String[] args){
		//1.创建工作簿
		XSSFWorkbook wb=new XSSFWorkbook();
		//2.创建工作表
		XSSFSheet sheet=wb.createSheet("工作表一");
		//3.创建行,第一行索引为0
		XSSFRow row=sheet.createRow(0); 
		//创建单元格
		row.createCell(0).setCellValue("三三今天也要加油鸭");
		row.createCell(1).setCellValue("CSDN博客");
		XSSFRow row1=sheet.createRow(1);
		row.createCell(0).setCellValue("Hello,world!");
		row.createCell(1).setCellValue("新春快乐");
		//输出流
		FileOutpotStream out=new FileOutputStream("E:\\poitest\\hello.xlsx");
		wb.write(out);
		//刷新内容
		out.flush(); 
		//释放资源
		out.close();
		wb.close();
		System.out.println("写入成功!");
}

实战练习

  • 读取excel数据到数据库
  • 将数据库数据写入到excel
  • 增加样式

示例读取表格如下:
在这里插入图片描述
由图可知,第一行的标题名称是不能放到实体类(Product)中,应从第二行开始将数据封装到实体类

从Excel读取数据代码

注意:读取时要时刻判断值是否为null

public static List<Product> readExcel(String Path) throws IOException{
//获取工作簿
 XSSFWorkbook wb=new XSSFWorkbook(path);
 //获取表
 XSSFSheet sheet=wb.getSheetAt(0);
 //获取行
int lastRowNum= sheet.getLastRowNum();
List<Product> plist=new ArrayList<>();
 for(i=1;i<=lastRowNum;i++){
	XSSFRow row=sheet.getRow(i);
	if(row!=null){
		//获取每个单元格,先放到list中,再放到Product中
		List<String> list=new ArrayList<>();
		for(Cell cell:row){
			if(cell!=null){
				cell.setCellType(Cell.CELL_TYPE_STRING);
				String value=vell.getStringCellValue(); //读取数据
				if(value!=null&&!"".equals(value)){
				list.add(value);
				}
				}
			}
			if(list.size()>0){
			Product product=new Product(Integer.parseInt(list.get(0)),list.get(1),Double.parseDouble(list.get(2)),Integer.parseInt(list.get(3)));
			plist.add(product);
			}
			
		}
	}
	return plist;
}

数据库读取数据后写入Excel表代码 并携带样式

示例写入表格如下:
在这里插入图片描述
由图可知,第一行的标题名称需要单独set值

注意:读取时要时刻判断值是否为null

public static String writeExcel(List<Product> plist,String path) throws IOException{
//生成工作簿,切记参数为空
 XSSFWorkbook wb=new XSSFWorkbook();
 //生成表
 XSSFSheet sheet=wb.getSheetAt("商品表");
 //设置样式
 XSSFCellStyle cellStyle=wb.createCellStyle();
 //设置背景颜色-粉色
 cellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex()); 
 //设置颜色填充规则--实心
 cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
 //创建字体样式
 XSSFFont font=xssfWorkbook.createFont();
 font.setFontName("黑体");
 font.setColor(IndexedColors.BLUE.getIndex());
 //将字体样式放入单元格样式中
 cellStyle.setFont(font);
 //创建第一行
 XSSFRow row=sheet.createRow(0);
//创建单元格内容
/* 链式编程: 
row.createCell(0).setCellValue("商品编号");
 row.createCell(1).setCellValue("商品名称");
 row.createCell(2).setCellValue("商品价格(单位:元/斤)");
 row.createCell(3).setCellValue("商品库存(单位:吨)"); */
XSSFCell cell=row.createCell(0);
cell.setCellValue("商品编号");
cell.setCellStyle(cellStyle);
XSSFCell cell=row.createCell(1);
cell.setCellValue("商品名称");
cell.setCellStyle(cellStyle);
XSSFCell cell=row.createCell(2);
cell.setCellValue("商品价格(单位:元/斤)");
cell.setCellStyle(cellStyle);
XSSFCell cell=row.createCell(3);
cell.setCellValue("商品库存(单位:吨)");
cell.setCellStyle(cellStyle);
//将list里的数据写入excel表
 for(int i=0;i<plist.size();i++){
	//从第二行开始写入数据
	XSSFRow row1=sheet.createRow(i+1); 
	row1.createCell(0).setCellValue(plist.get(i).getPid());
	row1.createCell(1).setCellValue(plist.get(i).getPname());
	row1.createCell(2).setCellValue(plist.get(i).getPrice());
	row1.createCell(3).setCellValue(plist.get(i).getPstock());
 }
	FileOutputStream op=new FileOutputStream(path);
	wb.write(op); 
	//刷新资源
	op.flush();
	op.close();
	wb.close();
}

导出结果:
在这里插入图片描述

以上是对excel文件的操作。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值