获取对应Excel文件的Workbook对象

一 代码

package WorkbookTest;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;

/**
* Copyright (C), 2020-2020, XXX有限公司
* FileName: Workbook
* Author:   cakin
* Date:     2020/1/18
* Description: 获取对应Excel文件的Workbook对象
*/
public class WorkbookTest {
    public static void main( String[] args ) {
        String file = "F:\\Javatest\\tempTest\\test.xlsx";
        File fileTest = new File(file);
        Workbook workbook = getWorkbook(fileTest);
        System.out.println("workbook:"+workbook);
    }

    public static Workbook getWorkbook( File file ) {
        Workbook wb = null;
        try {
            if (file.exists() && file.isFile()) {
                // 文件名
                String fileName = file.getName();
                // 文件扩展名
                String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
                // 文件输入流
                FileInputStream fileInputStream = new FileInputStream(file);
                try {
                    if ("xls".equals(extension)) { //Excel 2003
                        // 参考   https://www.cnblogs.com/fqfanqi/p/6172223.html
                        // 得到Excel工作簿对象
                        wb = new HSSFWorkbook(fileInputStream);
                    } else if ("xlsx".equals(extension)) { //Excel 2007
                        wb = new XSSFWorkbook(fileInputStream);
                    } else {
                        throw new IOException("not support the file type");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        // 关闭资源
                        System.out.println("关闭资源");
                        fileInputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return wb;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

二 测试

1 文件名存在时打印

关闭资源
workbook:Name: /xl/workbook.xml - Content Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml

2 文件不存在时打印

workbook:null

3 后缀名非法时的打印

java.io.IOException: not support the file type
关闭资源
    at WorkbookTest.WorkbookTest.getWorkbook(WorkbookTest.java:41)
    at WorkbookTest.WorkbookTest.main(WorkbookTest.java:19)
workbook:null

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值