使用POI读取和写出EXCEL文件(写出部分待完善)

来源:互联网 发布:淘宝店铺层级划分 编辑:程序博客网 时间:2024/06/05 02:18

Excel文件在工作中运行非常多,有时候需要我们结合数据读取和写出相应的数据,在这里写一个简单的demo方便以后的调用和学习:


读取文件部分:


首先,导入相应的JAR包

1、dom4j-1.6.1.jar  (一定要导入该包,不然POI解析的时候会报错) 

2、poi-3.8-20120326.jar

3、poi-ooxml-3.8-20120326.jar

4、poi-ooxml-schemas-3.8-20120326.jar

5、xmlbeans-2.3.0.jar


其次,代码部分

1、功能代码

public class ImportExcel {/** * 根据文件路径获取Excel中的数据 *  * @param FilePath文件路径 * @param num表头的数量(也就是多少列)            *  */public static void getDataFromExcel(String FilePath , int num) {// 判断是否是excel文件if (!FilePath.endsWith(".xls") && !FilePath.endsWith(".xlsx")) {System.out.println("导入的文件不是Excel文件类型!");}FileInputStream fis = null;Workbook workbook = null;// 构建一个输入流try {fis = new FileInputStream(FilePath);} catch (FileNotFoundException e) {e.printStackTrace();}try {if (FilePath.endsWith(".xls")) {// 获取2003版的EXCEL文件workbook = new HSSFWorkbook(fis);} else {// 获取2007版的EXCEL文件workbook = new XSSFWorkbook(fis);}} catch (IOException e) {e.printStackTrace();}// 获取一个EXCEL工作表Sheet sheet = workbook.getSheetAt(0);// 获取工作表表头Row rowHead = sheet.getRow(0);// 判断表头是否正确if (rowHead.getPhysicalNumberOfCells() != num) {System.out.println("表头数据不正确");} else {// 获取数据的总行数int rowNum = sheet.getLastRowNum();// 获取到的属性String name = null;int age = 0;// 获取EXCEL表中的所有数据for (int i = 1; i <= rowNum; i++) {// 获取第i行的数据Row row = sheet.getRow(i);// 获取第i行的第0列的数据Cell cell = row.getCell((short) 0);name = cell.getStringCellValue().toString();// 获取第i行的第1列的数据cell = row.getCell((short) 1);age = (int) cell.getNumericCellValue();System.out.println("name:" + name + "age:" + age);}}}}
2、测试代码

public class Test {public static void main(String[] args) {String FilePath = "D:/studentInfo.xlsx"; ImportExcel.getDataFromExcel(FilePath,2);}}

3、Excel中的数据

nameage张三21李四22王五23赵六21
4、输出情况

name:张三   age:21
name:李四   age:22
name:王五   age:23
name:赵六   age:21

最后,读取部分总结:

1、由于excel版本的不同,主要是2003和2007后缀的问题,解析的类也不一样,

xls 版本解析类:workbook = new HSSFWorkbook(fis);

xlsx 版本解析类:workbook = new XSSFWorkbook(fis);

所以一定要判断是哪种后缀,不然会报错

2、在读取数据的循环当中,注意数据类型,比如有列名,从第一行开始循环的话,因为有age不能转换成int类型,所以会报错。




0 0