Java使用POI读取excel文档教程

一:Poi的介绍

1.简介

1.由apache公司提供

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

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

2.使用前提(Java Dependency)

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

3.Poi包结构

HSSF——读写Microsoft Excel XLS

XSSF——读写Microsoft Excel XLSX

HWPF——读写Microsoft Word DOC

HLSF——提供读写Microsoft PowerPoint

4.优劣势

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

Poi:功能更加完善

二:Poi入门案例

Poi封装的对象:

XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:单元格

1.从Excel文件读取数据

第一步:准备一个Excel文件(hello.xlsx)

第二步:导入依赖

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

第三步:Java代码

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

另:使用普通for循环

        //开始索引 0 结束索引int lastRowNum = sheet.getLastRowNum();for (int i = 0; i <= lastRowNum; i++) {XSSFRow row = sheet.getRow(i);if (row != null) {short lastCellNum = row.getLastCellNum();for (int j = 0; j <= lastCellNum; j++) {XSSFCell cell = row.getCell(j);if (cell != null) {String value = cell.getStringCellValue();System.out.println(value);}}}}

第四步:控制台输出结果

Hello
World
!Process finished with exit code 0

2.向Excel文件写入数据

第一步:Java代码

public class Demo2 {public static void main(String[] args) throws IOException {//1、创建工作簿XSSFWorkbook workbook = new XSSFWorkbook();//2、创建工作表XSSFSheet sheet = workbook.createSheet("工作表一");//3、创建行XSSFRow row = sheet.createRow(0);//4、创建单元格row.createCell(0).setCellValue("Hello");row.createCell(1).setCellValue("world");row.createCell(2).setCellValue("!");XSSFRow row1 = sheet.createRow(1);row1.createCell(0).setCellValue("你好");row1.createCell(1).setCellValue("世界");row1.createCell(2).setCellValue("!");//输出流FileOutputStream out = new FileOutputStream("D:\\test.xlsx");workbook.write(out);out.flush();//释放资源out.close();workbook.close();System.out.println("写入成功");}
}

第二步:控制台输出结果

写入成功Process finished with exit code 0

第三步:查看生成的Excel文件

三、实战练习

目标:

读取Excel数据到数据库
将数据库数据写到Excel
增加样式

第一步:准备一个product.xslx

第二步:创建 product表

CREATE TABLE `product` (`pid` int(10) NOT NULL COMMENT '商品id',`pname` varchar(255) NOT NULL COMMENT '商品名称',`price` double(10,2) NOT NULL COMMENT '商品价格',`pstock` int(255) NOT NULL COMMENT '商品库存',PRIMARY KEY (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

第三步:导入 maven依赖

    <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version><scope>provided</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><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><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.6</version></dependency>

第四步:创建 JDBCUtils.java 工具类

public class JDBCUtils {private static DruidDataSource dataSource = null;static {Properties properties = new Properties();try {properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"));dataSource = new DruidDataSource();dataSource.setDriverClassName(properties.getProperty("jdbc.driver"));dataSource.setUrl(properties.getProperty("jdbc.url"));dataSource.setUsername(properties.getProperty("jdbc.username"));dataSource.setPassword(properties.getProperty("jdbc.password"));} catch (Exception e) {e.printStackTrace();}}public static DruidDataSource getDataSource() {return dataSource;}}

第五步:编写 druid.properties 配置文件

jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver

第六步:创建实体类 Product.java

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {private Integer pid;private String pname;private double price;private int pstock;
}

第七步:编写业务逻辑层 ProductService.java

public interface ProductService {void save(List<Product> productList);List<Product> findAll();
}

第八步:编写业务逻辑层实现类 ProductServiceImpl.java

public class ProductServiceImpl implements ProductService {private ProductDao productDao = new ProductDaoImpl();@Overridepublic void save(List<Product> productList) {for (Product product : productList) {productDao.save(product);}}@Overridepublic List<Product> findAll() {return productDao.findAll();}
}

第九步:编写数据持久层 ProductDao.java

public interface ProductDao {void save(Product product);List<Product> findAll();
}

第十步:编写数据持久层实现类 ProductDaoImpl.java

public class ProductDaoImpl implements ProductDao {private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());@Overridepublic void save(Product product) {String sql = "insert into product values(?,?,?,?)";jdbcTemplate.update(sql, product.getPid(), product.getPname(), product.getPrice(), product.getPstock());}@Overridepublic List<Product> findAll() {String sql = "select * from product";return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Product>(Product.class));}
}

最后一步:编写控制台 ConsoleView.java

public class ConsoleView {public static void main(String[] args) throws IOException {ProductService productService = new ProductServiceImpl();//通过键盘录入ScannerScanner sc = new Scanner(System.in);System.out.println("请输入你要选择的功能:1.导入 2.导出");int num = sc.nextInt();if (num == 1) {//1、导入//1.1、读取excel表格中的数据System.out.println("请输入您要读取文件的位置(不包含空格)");String path = sc.next();List<Product> productList = read(path);//1.2、将数据写入数据库中productService.save(productList);System.out.println("数据已存入数据库中");} else if (num == 2) {//2、导出//2.1、读取数据库中的数据List<Product> productList = productService.findAll();//2.2、将数据写入到excel表格中System.out.println("请输入要写入的文件位置");String path = sc.next();write(productList, path);System.out.println("写入成功");} else {System.out.println("输入有误,请重新启动");}}public static void write(List<Product> productList, String path) throws IOException {//创建工作簿XSSFWorkbook workbook = new XSSFWorkbook();//创建工作表XSSFSheet sheet = workbook.createSheet("商品");//修改样式XSSFCellStyle cellStyle = workbook.createCellStyle();cellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());//设置背景颜色cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);//设置颜色填充规则(实心)//设置字体XSSFFont font = workbook.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.setCellStyle(cellStyle);cell.setCellValue("商品编号");XSSFCell cell1 = row.createCell(1);cell1.setCellStyle(cellStyle);cell1.setCellValue("商品名称");XSSFCell cell2 = row.createCell(2);cell2.setCellStyle(cellStyle);cell2.setCellValue("商品价格(单位:元/斤)");XSSFCell cell3 = row.createCell(3);cell3.setCellStyle(cellStyle);cell3.setCellValue("商品库存(单位:吨)");for (int i = 0; i < productList.size(); i++) {XSSFRow sheetRow = sheet.createRow(i + 1);sheetRow.createCell(0).setCellValue(productList.get(i).getPid());sheetRow.createCell(1).setCellValue(productList.get(i).getPname());sheetRow.createCell(2).setCellValue(productList.get(i).getPrice());sheetRow.createCell(3).setCellValue(productList.get(i).getPstock());}FileOutputStream fileOutputStream = new FileOutputStream(path);workbook.write(fileOutputStream);fileOutputStream.flush();fileOutputStream.close();workbook.close();}public static List<Product> read(String path) throws IOException {List<Product> productList = new ArrayList<>();//获取工作簿XSSFWorkbook workbook = new XSSFWorkbook(path);//获取工作表XSSFSheet sheet = workbook.getSheetAt(0);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 value = cell.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)));productList.add(product);}}}return productList;}
}

运行结果:

读:

请输入你要选择的功能:1.导入 2.导出
1
请输入您要读取文件的位置(不包含空格)
D:\product.xlsx
数据已存入数据库中Process finished with exit code 0

写:

请输入你要选择的功能:1.导入 2.导出
2
请输入要写入的文件位置
D:\Goods.xlsx
写入成功Process finished with exit code 0

四、总结

1、在读写Excel表格中数据时,一定要先设置单元格中的数据格式

if (cell != null) {cell.setCellType(Cell.CELL_TYPE_STRING);//设置单元格中的数据格式String value = cell.getStringCellValue();if (value != null && !"".equals(value)) {list.add(value);}
}

使用Java POI读取excel文档相关推荐

  1. Java教程:使用POI读取excel文档(根据BV1bJ411G7Aw整理)

    Java教程:使用POI读取excel文档(根据BV1bJ411G7Aw整理) 最近公司需要我做一个导出Excel表格的功能,为此来学习一下POI,在这里记录一下学习笔记.B站直接搜BV1bJ411G ...

  2. poi读取Excel文档(.xls .xlsx)包含合并单元格

    例子: 结果: 开始:----------------------------------- 导入的poi <!-- https://mvnrepository.com/artifact/org ...

  3. POI 读取excel文档中输入日期格式为字符串

    通过cell.getCellStyle().getDataFormat();根据这个值进行时间.日期格式的判断: 时间格式 为了获取用户输入什么格式就显示什么格式,做以下整理: 通过对format值的 ...

  4. Java实战—POI操作Excel文档、读取、写入、合并单元格

    一.POI项目简介 POI全称 Poor Obfuscation Implementation,利用POI接口可以通过JAVA操作Microsoft office 套件工具的读写功能.官网:http: ...

  5. java后台处理excel_java后台利用Apache poi 生成excel文档提供前台下载示例

    之前在项目中会用到在java在后台把数据填入Word文档的模板来提供前台下载,为了自己能随时查看当时的实现方案及方便他人学习我写了这篇博客,访问量已经是我写的博客里第一了.于是乎我在学会用Java在后 ...

  6. java读取Excel文档 + 存入数据库

    序 在做项目的时候,我们有时想要读取Excel类型的文档,把表格里面的数据进行处理,比如把成绩Excel文档存储到数据库对应的表.而这时却不知道该如何操作,接下来我将讲解这个流程.以下面的数据为例 总 ...

  7. 使用POI读取word文档

    使用POI 读取word 文档(word 2003和2007) 最近在给客户做系统的时候,用户提出需求,要能够导入 word 文件,现在 microsoft word 有好几个版本 97.2003.2 ...

  8. 关于poi读取word文档修改后输出乱码问题 poi word 乱码

    java用poi读取word文档的确很容易.不过不同版本之间差别还是挺大的.目前只是试出了poi-3.8-beta4这个版本编辑word内容后输出不是乱码.最新官方版本都是乱码,不知道为什么.贴出代码 ...

  9. python无法读取excel文字_Python帮你做Excel——读取Excel文档

    相信很多坐在办公室上班的朋友每天都需要处理大量的数据,我们常常用Excel制作电子表格来帮助我们处理它们.这当然是一种非常好的做法,但是我相信大家都会发现,很多表格的内容其实大同小异,常常需要我们把同 ...

最新文章

  1. python numpy np.fromstring()函数(从字符串文本中提取数字,返回一维数组)(爬虫提取数字挺好用的)
  2. mycli mysql_MyCLI :易于使用的 MySQL/MariaDB 客户端
  3. PaaS、DevOps、OpenShift与业务中台的实现
  4. 值得收藏的数据库基础总结!
  5. iis中间件_.NET Core技术研究中间件的由来和使用
  6. Oracle Primavera P6EPPM Mobile/App 安卓移动端分享(长期更新)
  7. 信用卡分销系统如何获客
  8. A-priori算法
  9. Windows7安装无法识别硬盘分区
  10. 常用广告过滤规则整理
  11. 文本数据分析实战【数据清洗、统计分析、可视化展示、情感分析】
  12. 基于JAVA出差报销管理系统
  13. 轻松几步获得上万点击率(三)
  14. android 7.0 新功能介绍(Nougat)
  15. Javase 笔记知识点概要
  16. 脱胎于沃尔沃的Polestar 2浮出水面,它真能挑战Model 3吗?
  17. php7.2.3下载,最新PHP编程软件v7.3.2.0 官方版下载地址电脑版-锐品软件
  18. 主板上还剩啥?CPU整合GPU/北桥/南桥
  19. 【项目实战19】k8s(5)—service服务(IPVS均衡负载)
  20. 对接华为存储iSCSI

热门文章

  1. 弘辽科技:多多进宝推广前,必知的五个操作常见问答
  2. 最新谷歌浏览器乱码解决方案
  3. 测试开发实习日记(DAY3)
  4. 用计算机做一克拉等于多少克,一克拉等于多少克 钻石克拉转换成分是怎么转换的...
  5. iOS开发证书申请详细教程(真机调试测试使用)
  6. 面试总结:京东现场面试0917
  7. 网孔分析法和网络定理
  8. ncnn之八:ncnn量化(post-training quantization)三部曲 - ncnn2int8
  9. 欧洲彼得·德鲁克协会任命美国项目管理协会的Sunil Prashara担任其国际咨询委员会委员
  10. SPL - QQ空间日志查看工具 v1.1.0.441