POI、JAVA、Excel,通过URL创建WorkBook

从文件的网络路径创建Workbook ,直接上代码,不清楚的可以留言

创建workBook的入口方法,方法内部调用的代码片段已经贴在下面。

// filePath是文件的网络路径,比如:http://hahaha.com/template.xlsx
protected static WorkBook createWorkBook(String filePath, String fileName) throws IOException {
     
    InputStream inputStream = FileUtils.getInputStream(filePath, fileName);
    Workbook workbook = WorkBookUtil.createWorkBook(inputStream, ExcelTypeEnum.XLSX);
    return workbook ;
}

FileUtils类,需要对URL中的文件名称进行URL转码处理

public static InputStream getInputStream(String url, String fileName) throws IOException {
     
    // url = url.replace(" ", "%20");
    String[] split = fileName.split("\\.");
    if (split.length > 0) {
     
        fileName = split[0];
    }
    // URLEncoder主要解决文件名称是中文的问题
    String newFileName = URLEncoder.encode(fileName, "UTF-8");
    url = url.replace(fileName, newFileName).replace(" ", "%20");
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setReadTimeout(5000);
    connection.setConnectTimeout(5000);
    connection.setRequestMethod("GET");
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
     
        InputStream inputStream = connection.getInputStream();
        // new BufferedInputStream(inputStream)主要解决HttpInputStream不支持.mark(int)的问题
        return new BufferedInputStream(inputStream);
    }
    return null;
}

WorkBookUtil工具类代码片段,ExcelCommonException是自定义异常类

private static final int ROW_ACCESS_WINDOW_SIZE = 500;

public static Workbook createWorkBook(InputStream inputStream, ExcelTypeEnum excelType) throws IOException {
     
    if (ExcelTypeEnum.UNKNOWN.equals(excelType)) {
     
        throw new ExcelCommonException("未知的文件类型");
    }
    
    if (ExcelTypeEnum.XLSX.equals(excelType)) {
     
        return new SXSSFWorkbook(new XSSFWorkbook(inputStream), ROW_ACCESS_WINDOW_SIZE);
    }

    HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
    return workbook;
}

ExcelTypeEnum 枚举类

public enum  ExcelTypeEnum {
     
    /**
     * xls
     */
    XLS(".xls"),

    /**
     * xlsx
     */
    XLSX(".xlsx"),

    /**
     * 未知
     */
    UNKNOWN("UNKNOWN"),
    ;

    ExcelTypeEnum(String value) {
     
        this.setValue(value);
    }

    private String value;

    public String getValue() {
     
        return value;
    }

    public void setValue(String value) {
     
        this.value = value;
    }
}

你可能感兴趣的:(POI,excel,url,poi)