Newer
Older
newfiber-termite / newfiber-common / newfiber-common-office / src / main / java / com / newfiber / utils / OfficeUtil.java
package com.newfiber.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * office公共工具
 * date: 2023/3/28 下午 06:26
 *
 * @author: LuFan
 * @since JDK 1.8
 */
public class OfficeUtil {

    /**
     * 二进制文件流返回给调用方
     * date: 2023/4/27 下午 01:58
     * @author: LuFan
     * @since JDK 1.8
     */
    public static void exportByteStreamToClient(HttpServletResponse res, byte[] bytes, String fileName) throws IOException {
        res.setCharacterEncoding("UTF-8");
        // attachment是以附件的形式下载,inline是浏览器打开
        res.setHeader("Content-Disposition", "attachment;filename="+ fileName);
        res.setContentType("text/plain;UTF-8");
        ServletOutputStream os = res.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }

    /**
     * 根据文件url获取文件
     *
     * @param urlStr 文件url
     * @return InputStream
     * date: 2023/3/29 上午 11:28
     * @author: LuFan
     * @since JDK 1.8
     */
    public static InputStream getFile(String urlStr) {
        InputStream inputStream = null;
        try {
            URL url = new URL(java.net.URLDecoder.decode(urlStr, "utf-8"));
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(3 * 1000);
            urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = urlConnection.getInputStream();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return inputStream;
    }

    public static void exportWord(byte[] bytes, String exportFile) throws Exception {
        try {
            if (bytes != null) {
                OutputStream outputStream = new FileOutputStream(exportFile);
                InputStream is = new ByteArrayInputStream(bytes);
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = is.read(buff)) != -1) {
                    outputStream.write(buff, 0, len);
                }
                is.close();
                outputStream.close();
            }
        } catch (Exception e) {
            throw (e);
        }
    }
}