POI读写Excel

1. 添加依赖

	<dependency>
	    <groupId>org.apache.poi</groupId>
	    <artifactId>poi</artifactId>
	    <version>4.0.1</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
	<dependency>
	    <groupId>org.apache.poi</groupId>
	    <artifactId>poi-ooxml</artifactId>
	    <version>4.0.1</version>
	</dependency>

如果zhi 只添加poi会报错,需要再添加poi-ooml

2. POI对Excel的支持需要根据不同的Excel版本使用不同的包

org.apache.poi.hssf:2003(xls后缀)

org.apache.poi.xssf.:2007+(xlsx后缀)

其中多数方法命名也类似,下面的总结都使用的是“xssf”

(1) 读文件:

File fi=new File(resExcelPath);
InputStream in = new FileInputStream(fi);
XSSFWorkbook wb = new XSSFWorkbook(in);
//读取所有内容
XSSFSheet sheet = wb.getSheetAt(0);
//保存原有公式
sheet.setForceFormulaRecalculation(true);

(2) 写文件

//写入已有单元格
sheet.getRow(1).getCell(2).setCellValue(*****);

//创建单元格
//行和列都不存在时
cell = sheet.createRow(row).createCell(col);
//行存在,列不存在时
cell = sheet.getRow(row).createCell(col);

//合并单元格
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));

如果行已存在,再用createRow(row).createCell(col)就会把原有的内容删除

(3) 设置格式

CellStyle style = wb.createCellStyle();

//对齐方式
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setAlignment(HorizontalAlignment.LEFT);
//边框
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);

cell.setCellStyle(style);

(4)保存

//保存到新的路径下
FileOutputStream out = new FileOutputStream(desExcelPath);
wb.write(out);
out.close();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值