Java架构-Apache POI Excel

1,366 阅读2分钟

相信在项目中,对数据进行动态导出这是一个比较常见的功能。对于数据导出我们可以使用Apache-POI这个框架来帮我来进行Excel的写入与读取。下面就用代码来实现Apache POI写入与读取excel文件。

1、Apache POI基本概念

下面将简单的描述一下当进行Excel读取与写入的时候要使用到的基本类。

  1. HSSF 为前缀的类名表示操作的是Microsoft Excel 2003文件。
  2. XSSF 为前缀的类名表示操作的是Microsoft Excel 2007或以后的版本
  3. XSSFWorkbook 和 HSSFWorkbook表示一个Excel的Workbook.
  4. HSSFSheet 和 XSSFSheet 表示一个Excel的Worksheet.
  5. Row 表示一个Excel行
  6. Cell 表示当前Row中一个Cell.

2、下载Apache POI

在项目中是使用Maven来管理Jar依赖的,所以在Pom.xml添加以下依赖:

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

3、写入一个Excel文件

下面的代码将会简单的展示使用Apache POI写入一个Excel文件。数据将会写入到XSSFWorkbook对象中。

ApachePOIExcelWrite.java
package com.weimob.o2o.carl.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ApachePOIExcelWrite {

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main(String[] args) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Data types in Java");
        Object[][] dataTypes = {
                {"DataType", "Type", "Size(in bytes)"},
                {"int", "Primitive", 2},
                {"float", "Primitive", 4},
                {"double", "Primitive", 8},
                {"char", "Primitive", 1},
                {"String", "Non-Primitive", "No fixed size"}
        };

        int rowNum = 0;
        System.out.println("Creating excel");
        for(Object[] dataType : dataTypes){
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for(Object field : dataType){
                Cell cell = row.createCell(colNum++);
                if(field instanceof String){
                    cell.setCellValue((String) field);
                } else if (field instanceof Integer){
                    cell.setCellValue((Integer) field);
                }
            }
        }
        try {
            FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
            workbook.write(outputStream);
            workbook.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Done");

    }

}

你将会在你项目所在的磁盘中的tmp文件夹中得到以下的excel文件:

4、读取一个Excel文件

下面的代码展示如何使用Apache POI读取Excel文件。getCellTypeEnum方法在 3.15 中不推荐使用并且会在 4.0 版本中将会改名为:getCellType.

ApachePOIExcelRead.java
package com.weimob.o2o.carl.poi;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

public class ApachePOIExcelRead {

    private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";

    public static void main(String[] args) {
        try {
            FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet dataTypeSheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = dataTypeSheet.iterator();
            while(iterator.hasNext()){
                Row currentRow = iterator.next();
                Iterator<Cell> cellIterator = currentRow.iterator();
                while(cellIterator.hasNext()){
                    Cell currentCell = cellIterator.next();
                    //getCellTypeEnum shown as deprecated for version 3.15
                    //getCellTypeEnum ill be renamed to getCellType starting from version 4.0
                    if(currentCell.getCellTypeEnum() == CellType.STRING){
                        System.out.print(currentCell.getStringCellValue() + "--");
                    } else if(currentCell.getCellTypeEnum() == CellType.NUMERIC){
                        System.out.print(currentCell.getNumericCellValue() + "--");
                    }
                }
                System.out.println();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

你的控制台将会输出以下代码:

为什么某些人会一直比你优秀,是因为他本身就很优秀还一直在持续努力变得更优秀,而你是不是还在满足于现状内心在窃喜!

合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!

To-陌霖Java架构

分享互联网最新文章 关注互联网最新发展