Java中使用POI操作Excel

开发中经常需要使用POI来解析Excel表格,这是非常常规的操作。这里简单的分享下POI中HSSF和XSSF来操作Excel。使用POI之前你需要在maven中引入以下依赖:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15-beta2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15-beta2</version>
</dependency>
写个简单的类来测试下使用POI创建表格:
import org.apache.commons.lang.RandomStringUtils;
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 java.io.File;
import java.io.FileOutputStream;

/**
* POI创建Excel
*/
public class POICreateExcelTest {
    public static void main(String[] args) throws Exception {
        String []title = {"订单ID","流水号"};
        //创建HSSF工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个Sheet页
        HSSFSheet sheet = workbook.createSheet();
         //创建第一行(一般是表头)
        HSSFRow row0 = sheet.createRow(0);
        //创建列
        HSSFCell cell = null;
        //设置表头
        for (int i = 0; i <title.length ; i++) {
            cell=row0.createCell(i);
            cell.setCellValue(title[i]);
        }
        //填充20行数据
        for (int i = 1; i < 20; i++) {
            HSSFRow row =sheet.createRow(i);
            HSSFCell cell1 = row.createCell(0);
            cell1.setCellValue(RandomStringUtils.randomNumeric(18));
            HSSFCell cell2 = row.createCell(1);
            cell2.setCellValue(RandomStringUtils.randomNumeric(12));
        }
        //保存到本地
        File file = new File("D:/test.xls");
        FileOutputStream outputStream = new FileOutputStream(file);
        //将Excel写入输出流中
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
成功创建xls格式的Excel并把内容写入到Excel中。再写个类测试POI解析Excel:
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 java.io.File;
import java.io.FileInputStream;

/**
* POI解析Excel
*/
public class POIReadExcelTest {

    public static void main(String[] args) throws Exception {
        //读取本地文件
        File file = new File("D:/test.xls");
        FileInputStream fis = new FileInputStream(file);
        HSSFWorkbook workbook = new HSSFWorkbook(fis);
        HSSFSheet sheet1 = workbook.getSheetAt(0);
        //获取当前sheet页的总行数
        int totalRowNums = sheet1.getPhysicalNumberOfRows();
        for (int i = 0; i < totalRowNums; i++) {
            Row row = sheet1.getRow(i);
            //获取每一行的总列数
            int totalCellNums = row.getPhysicalNumberOfCells();
            for (int j = 0; j < totalCellNums; j++) {
                Cell cell = row.getCell(j);
                String value = getCellValue(cell);
                System.out.println(value);
            }
        }
    }

    public static String getCellValue(Cell cell) {
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            Double d = cell.getNumericCellValue();
            return String.valueOf(d.intValue());
        }
        return String.valueOf(cell.getStringCellValue());
    }
}
可以看到,通过POI的HSSF对象操作excel是xls格式(97-2003版本的Excel的标准后缀),那么我们现在常常见到的往往是xlsx(2007版本以后的office),这就需要使用HSSF的plus版,即POI的XSSF对象来操作Excel了。

改造下刚才创建表格的HSSF为XSSF,换汤不换药:
import org.apache.commons.lang.RandomStringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;

/**
* POI创建Excel
*/
public class POICreateExcelTest {
    public static void main(String[] args) throws Exception {
        String[] title = {"订单ID", "流水号"};
        //创建HSSF工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建一个Sheet页
        XSSFSheet sheet = workbook.createSheet();
        //创建第一行(一般是表头)
        XSSFRow row0 = sheet.createRow(0);
        //创建列
        XSSFCell cell = null;
        //设置表头
        for (int i = 0; i < title.length; i++) {
            cell = row0.createCell(i);
            cell.setCellValue(title[i]);
        }
        //填充20行数据
        for (int i = 1; i < 20; i++) {
            XSSFRow row = sheet.createRow(i);
            XSSFCell cell1 = row.createCell(0);
            cell1.setCellValue(RandomStringUtils.randomNumeric(18));
            XSSFCell cell2 = row.createCell(1);
            cell2.setCellValue(RandomStringUtils.randomNumeric(12));
        }
        //保存到本地
        File file = new File("D:/test.xlsx");
        FileOutputStream outputStream = new FileOutputStream(file);
        //将Excel写入输出流中
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}

还有一点要注意的是,使用HSSF导出时,在poi3.7版本以下时,最大导出量为65536左右,poi版本3.7++以后,更多的使用XSSF对象操作Excel,最大支持百万量级别。

完整的导入导出功能代码参见:Java导入导出功能总结

猜你喜欢

转载自blog.csdn.net/fanrenxiang/article/details/81066497