apache poi基本操作

apache poi基本操作

依赖导入

<!--apache poi依赖-->
<!--03xls版本依赖-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.0.0</version>
</dependency>
<!--07xlsx版本依赖-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.0.0</version>
</dependency>

poi常用对象

//创建03版本xls的工作簿对象
Workbook workbook =new HSSFWorkbook(); 
//创建07版本xlsx的工作簿对象
Workbook workbook =new XSSFWorkbook();
//创建工作簿07大数据量xlsx对象
Workbook workbook =new SXSSFWorkbook();

基本的excel生成操作

excel生成

//生成07版本只需要对象换成SXSSFWorkbook,后缀改为xlsx即可
public static void testPoiWriter() throws Exception {
    //创建工作簿03xls对象
    Workbook workbook = new HSSFWorkbook();
    //创建sheet页对象
    Sheet sheet = workbook.createSheet();
    //创建行 0开始
    Row row = sheet.createRow(0);
    //创建行中的单元格 0开始
    Cell cell = row.createCell(0);
    cell.setCellValue("你好啊");
    //创建输出对象
    FileOutputStream fileOutputStream = new FileOutputStream(("D:\\lwp\\test\\简单的excel生成.xls"));
    //excel数据写入流
    workbook.write(fileOutputStream);
    //关闭流
    fileOutputStream.close();
}

大数据量生成测试

测试代码

public static void testPoiWriterByBigDta() throws Exception {
    //创建工作簿03xls对象
    Workbook workbook = new HSSFWorkbook();
    //创建sheet页对象
    Sheet sheet = workbook.createSheet();
    long beginTime = System.currentTimeMillis();
    //创建行 0开始
    for (int i = 0; i < 65537; i++) {
        Row row = sheet.createRow(i);
        for (int j = 0; j < 10; j++) {
            //创建行中的单元格 0开始
            Cell cell = row.createCell(j);
            cell.setCellValue(i+"-"+j);
        }
    }
    //创建输出对象
    FileOutputStream fileOutputStream = new FileOutputStream(("D:\\lwp\\test\\简单的excel生成.xls"));
    //excel数据写入流
    workbook.write(fileOutputStream);
    long endTime = System.currentTimeMillis();
    System.out.println("耗时:"+(double)(endTime-beginTime)/1000);
    //关闭流
    fileOutputStream.close();
}

测试结论

使用HSSFWorkbook对象耗时:1.975秒  
	优点:速度快 
	缺点:1、限制为65536行,超出报错 2、占用空间大,上述代码生成文件占用空间16,824kb
使用XSSFWorkbook对象耗时:10.273秒  
	优点:1、无限制行数 2、占用空间小,上述代码生成文件占用空间3,688kb
	缺点:速度慢
使用SXSSFWorkbook对象耗时:1.306秒 
	优点:1、无限制行数 2、速度快 3、占用空间小,上述代码生成文件占用空间2,173kb
	可能生成临时文件,写完文件后需要加入清除代码
	workbook.write(fileOutputStream);
    //清除临时文件
    ((SXSSFWorkbook)workbook).dispose();

基本的excel读取操作

excel基本读取

public static void testPoiRead() throws Exception {
    String path="D:\\lwp\\test\\student.xls";
    FileInputStream fileInputStream = new FileInputStream(path);
    //创建工作簿03xls对象
    Workbook workbook = new HSSFWorkbook(fileInputStream);
    //获取sheet,可通过名称指定读取
    Sheet sheet = workbook.getSheetAt(0);
    //获取第一行
    Row row = sheet.getRow(0);
    //获取第一行的第一个单元格对象
    Cell cell = row.getCell(0);
    //获取第一行的第一个单元格内容
    String resultValue=cell.getStringCellValue();
    System.out.println(resultValue);
    //关闭流
    fileInputStream.close();
}

按类型读取所有数据

public static void testPoiRead() throws Exception {
    String path="D:\\lwp\\test\\student.xls";
    FileInputStream fileInputStream = new FileInputStream(path);
    //创建工作簿03xls对象
    Workbook workbook = new HSSFWorkbook(fileInputStream);
    //获取sheet,可通过名称指定读取
    Sheet sheet = workbook.getSheetAt(0);
    //获取第一行标题
    Row titleRow = sheet.getRow(0);
    //获取当前行有多少列
    int countCells = titleRow.getPhysicalNumberOfCells();
    //遍历所有列读取标题
    for (int i = 0; i < countCells; i++) {
        Cell cell = titleRow.getCell(i);
        if(cell!=null){
            //获取每一列的值
            String titleCell = cell.getStringCellValue();
            System.out.print(titleCell+"|");
        }
    }
    //换行
    System.out.println();
    //获取当前sheet一共有多少行
    int countRows = sheet.getPhysicalNumberOfRows();
    //遍历除标题的所有行
    for (int i = 1; i < countRows; i++) {
        //获得一共多少列进行遍历
        Row row = sheet.getRow(i);
        int countCell = row.getPhysicalNumberOfCells();
        for (int j = 0; j < countCell; j++) {
            Cell cell = row.getCell(j);
            String value="";
            if(cell!=null){
                if(cell.getCellType()==CellType.STRING){
                    value = cell.getStringCellValue();
                }else if(cell.getCellType()==CellType.BOOLEAN){
                    value = String.valueOf(cell.getBooleanCellValue());
                }else if(cell.getCellType()==CellType.NUMERIC){
                    //5.0之前使用HSSFDateUtil.isCellDateFormatted
                    if(DateUtil.isCellDateFormatted(cell)){
                        //如果是日期类型
                        Date dateCellValue = cell.getDateCellValue();
                        value=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dateCellValue);
                    }else{
                        //数值类型poi5.0之前的解决方案
                        //                            cell.setCellType(CellType.STRING);
                        //                            value=cell.getStringCellValue();
                        //数值类型 poi5.0之后的解决方案
                        double numericCellValue = cell.getNumericCellValue();
                        //stripTrailingZeros():去除末尾多余的0,toPlainString():输出时不用科学计数法
                        value = new BigDecimal(String.valueOf(numericCellValue)).toPlainString();
                    }
                }else if(cell.getCellType()==CellType.BLANK){
                    //空、啥也不干
                }else if(cell.getCellType()==CellType.ERROR){
                    System.out.println("数据类型错误!");
                }
                System.out.print(value+"|");
            }
        }
        System.out.println();
    }
    //关闭流
    fileInputStream.close();
}

公式读取

public static void testPoiRead() throws Exception {
    String path="D:\\lwp\\test\\公式.xls";
    FileInputStream fileInputStream = new FileInputStream(path);
    //创建工作簿03xls对象
    Workbook workbook = new HSSFWorkbook(fileInputStream);
    //获取sheet,可通过名称指定读取
    Sheet sheet = workbook.getSheetAt(0);
    //获取第4行(第四行为公式计算)
    Row row = sheet.getRow(3);
    //拿到计算公式对象
    FormulaEvaluator fe=new HSSFFormulaEvaluator((HSSFWorkbook)workbook);
    //获取指定单元格
    Cell cell = row.getCell(0);
    //获取单元格类型
    CellType cellType = cell.getCellType();
    if(cellType==CellType.FORMULA){//如果当前单元格类型为公式
        //获取单元格的公式
        String cellFormula = cell.getCellFormula();
        System.out.println("公式:"+cellFormula);
        //计算
        CellValue evaluate = fe.evaluate(cell);
        //获取公式计算后的String值
        String resultValue = evaluate.formatAsString();
        System.out.println("计算的值:"+resultValue);
    }
    //关闭流
    fileInputStream.close();
}
posted @ 2021-07-12 23:13  幸运刘  阅读(195)  评论(0)    收藏  举报