使用java字節流拷貝excel文件,部分內容有問題解決

方法一:

 
    public static void copy(File src, File des) throws IOException {
        FileOutputStream writer = null;
        FileInputStream reader = null;
        BufferedInputStream bufR = null;
        BufferedOutputStream bufW = null;
        try {
            reader = new FileInputStream(src);
            writer = new FileOutputStream(des);
            bufR = new BufferedInputStream(reader);
            bufW = new BufferedOutputStream(writer);
            int temp = 0;
            while ((temp = bufR.read()) != -1) {
                bufW.write(temp);
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        } finally {

            try {
                if (bufR != null) {
                    reader.close();
                    bufR.close();
                }
                if (bufW != null) {
                    writer.close();
                    bufW.close();
                }
            } catch (IOException e) {
                log.error("關閉連接失敗", e);
            }
        }

    }

這種方法複製excel會有部分格式丟失的問題

例如excel的批註以及顏色沒有出來

方法二:

 public static byte[] readFileToByteArray(String src) {
        // 文件輸入流(需要關閉)
        InputStream is = null;
        try {
            is = new FileInputStream(new File(src));
            // 字節數組輸出流(不需要關閉)
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024 * 1];
            int len;
            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


public static void writeByteArrayToFile(byte[] datas, String destFileName) {
        // 文件輸出流(需要關閉)
        OutputStream os = null;
        try {
            // 字節數組輸入流(不需要關閉)
            InputStream is = new ByteArrayInputStream(datas);
            os = new FileOutputStream(new File(destFileName));

            byte[] buf = new byte[1024];
            int len;
            while (((len = is.read(buf)) != -1)) {
                os.write(buf, 0, len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

此方法能成功導出,先讀再寫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章