package com.demo.excel;

import com.demo.pojo.Student;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List; import static javax.xml.bind.JAXBIntrospector.getValue; /**
* Created by xfma on 2017/1/19.
*/
public class ReadExcel { final static String excelFileName = "F:/Test.xls"; public static void main(String[] args) {
try {
createExcel(createStudent());
List<Student> list = readExcel(excelFileName);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getName() + "\t" + list.get(i).getAge() + "\t" + list.get(i).getSchool() + "\t" + list.get(i).getAddress());
}
} catch (Exception e) {
e.getStackTrace();
} } /**
* 读Excel
*
* @param excelFileName 文件名
* @return
* @throws Exception
*/
public static List<Student> readExcel(String excelFileName) throws Exception { boolean isExcel2003 = true;
if (!excelFileName.endsWith("xls")) {
isExcel2003 = false;
}
File file = new File(excelFileName);
FileInputStream fis = new FileInputStream(file);
Workbook workbook = null;
/*excel2003和2007不是用同一个对象读取的*/
if (isExcel2003) {
workbook = new HSSFWorkbook(fis);
} else {
workbook = new XSSFWorkbook(fis);
} Sheet sheet = workbook.getSheetAt(0);//得到第0个Sheet
sheet.getLastRowNum();
List<Student> list = new ArrayList<Student>();
for (int r = 0; r < sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r + 1);//越过标题,从第二行读
if (row != null) {
Student student = new Student();
Cell name = row.getCell(0);
Cell age = row.getCell(1);
Cell address = row.getCell(2);
Cell school = row.getCell(3);
student.setName(getValue(name).toString());
float f = Float.parseFloat(getValue(age).toString());
student.setAge((int) f);
student.setAddress(getValue(address).toString());
student.setSchool(getValue(school).toString());
list.add(student);
}
}
return list;
} /**
* 生成Excel
*
* @param list 对象集合
* @throws Exception
*/
public static void createExcel(List<Student> list) throws Exception {
//1.创建一个HSSFWorkbook对象,每个HSSFWorkbook对应一个新的Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
//2.在HSSFWorkbook中添加一个sheet,对应Excel中的一个sheet表
HSSFSheet sheet = workbook.createSheet("学生信息表");
String[] cells = new String[]{"姓名", "年龄", "地址", "学校"};//表头
int rowSize = list.size() + 1;//从第二条开始读,去掉标题
for (int r = 0; r < rowSize; r++) {
HSSFRow row = sheet.createRow(r);
for (int c = 0; c < cells.length; c++) { HSSFCell cell = row.createCell(c);
if (r == 0) {
cell.setCellValue(cells[c]);//创建表头
} else {
/*往表内写数据*/
int index = r - 1;//从第一条数据往里面写
switch (c) {
case 0:
cell.setCellValue(list.get(index).getName());
continue;
case 1:
cell.setCellValue(list.get(index).getAge());
continue;
case 2:
cell.setCellValue(list.get(index).getAddress());
continue;
case 3:
cell.setCellValue(list.get(index).getSchool());
continue;
}
} }
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} /**
* 创建示例
*
* @return
*/
public static List<Student> createStudent() {
List<Student> list = new ArrayList<Student>();
Student s1 = new Student("小黑", 18, "上海浦东", "复旦大学");
Student s2 = new Student("小白", 19, "上海普陀", "同济大学");
Student s3 = new Student("小玉", 22, "上海黄埔", "上海交通大学");
Student s4 = new Student("小红", 20, "上海静安", "上海财经大学");
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
return list;
}
}

pojo:

package com.demo.pojo;

import java.io.Serializable;

/**
* Created by xfma on 2017/1/19.
*/
public class Student implements Serializable{
private String name;
private Integer age;
private String address;
private String school; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getSchool() {
return school;
} public void setSchool(String school) {
this.school = school;
} public Student(String name, Integer age, String address, String school) {
this.name = name;
this.age = age;
this.address = address;
this.school = school;
} public Student() {
}
}

pom.xml:

<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<!-- poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>

java使用poi读写Excel的更多相关文章

  1. java 使用POI读写Excel文件(兼容2003、2007)

    package com.jadyer.demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOExce ...

  2. Java Struts2 POI创建Excel文件并实现文件下载

    Java Struts2 POI创建Excel文件并实现文件下载2013-09-04 18:53 6059人阅读 评论(1) 收藏 举报 分类: Java EE(49) Struts(6) 版权声明: ...

  3. jxl读写excel, poi读写excel,word, 读取Excel数据到MySQL

    这篇blog是介绍: 1. java中的poi技术读取Excel数据,然后保存到MySQL数据中. 2. jxl读写excel 你也可以在 : java的poi技术读取和导入Excel了解到写入Exc ...

  4. java使用POI实现excel文件的读取,兼容后缀名xls和xlsx

    需要用的jar包如下: 如果是maven管理的项目,添加依赖如下: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --&g ...

  5. [转]POI读写Excel 修改

    [转]POI读写Excel 修改 一.Excel基础 二.HSSF概况 三.通过usermodel读取文件 四.通过usermodel写入文件 五.通过eventusermodel读取文件 六.HSS ...

  6. Java之POI读取Excel的Package should contain a content type part [M1.13]] with root cause异常问题解决

    Java之POI读取Excel的Package should contain a content type part [M1.13]] with root cause异常问题解决 引言: 在Java中 ...

  7. poi读写Excel

    poi读写Excel 对于一个程序员来说,文件操作是经常遇到的,尤其是对Excel文件的操作. 在这里介绍一下我在项目中用到的一个操作Excel的工具——POI.关于POI的一些概念,网络上很多,详细 ...

  8. 《手把手教你》系列技巧篇(六十六)-java+ selenium自动化测试 - 读写excel文件 - 上篇(详细教程)

    1.简介 在自动化测试,有些我们的测试数据是放到excel文件中,尤其是在做数据驱动测试的时候,所以需要懂得如何操作获取excel内的内容.由于java不像python那样有直接操作Excle文件的类 ...

  9. 《手把手教你》系列技巧篇(六十七)-java+ selenium自动化测试 - 读写excel文件 - 中篇(详细教程)

    1.简介 前面介绍了POI可以操作excel,也简单的提到另一个操作excle的工具,本篇介绍一个其他的可以操作excel的工具,但是这个工具有一个前提,excel文件版本只能是97-2003版本,如 ...

随机推荐

  1. XJTU Summer Holiday Test 1(Brackets in Implications-构造)

    B - Brackets in Implications Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & ...

  2. Rails中nil? empty? blank? present?的区别

    .nil? Ruby方法 .nil?方法被放置在Object类中,可以被任何对象调用,如果是nil则返回true 在Rails中只有nil对象才会返回true nil.nil? #=> true ...

  3. Matlab中特征向量间距离矩阵的并行mex程序

    在matlab中, 有n个向量(m维)的矩阵Mat(n, m) 要计算任两个向量间的距离, 即距离矩阵, 可使用以下的并行算法以加速: #include <iostream> #inclu ...

  4. Oracle基础(一) Oracle的安装和卸载

    一.数据库的基本概念. 数据库就是数据存储的仓库,可以更快的查询.处理.统计数据,还可以保持数据的一致性.共享性和安全性,方便只能的分析,产生新的有用的信息. 1.数据库的发展阶段: (1)萌芽阶段: ...

  5. S3:代理模式 Proxy

    为其他对象提供一种代理以控制对这个对象的访问. 使用场合: 1.远程代理:为一个对象在不同的地址空间提供局部代表,隐藏对象存在于不同地址空间的事实.2.虚拟代理:根据需要创建开销很大的对象,通过它来存 ...

  6. oracle字符串处理相关

    函数 返回 描述 例子 to_char(timestamp, text) text 把 timestamp 转换成 string to_char(timestamp 'now','HH12:MI:SS ...

  7. Docker镜像Export导出和Import导入

    在使用Docker时最头痛的无非无法获取仓库镜像,我们可以通过Export导出镜像备份,通过import导入镜像.导出镜像是通过容器进行导出,下面来看镜像对应的容器: root@default:~# ...

  8. Atitit.跨语言系统服务管理器api兼容设计

    Atitit.跨语言系统服务管理器api兼容设计 1. Common api,兼容sc ,service control??1 1.1. 服务创建,use sc1 1.2. 服务delete ,use ...

  9. JSTL JSP页面推断某个cookie的值和读取值....

    <c:if test="${cookie['woshop'].value eq '1'}">                 <div>           ...

  10. vmstat 命令

    vmstat是Virtual Meomory Statistics(虚拟内存统计)的缩写,可对操作系统的虚拟内存.进程.CPU活动进行监控.他是对系统的整体情况进行统计,不足之处是无法对某个进程进行深 ...