日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

EasyExcel實現(xiàn)追加寫入文件

作者:Lincain 更新時間: 2022-07-11 編程語言

最近工作中需要將數(shù)據(jù)寫入到excel中,寫入的方式分兩類,一類是直接寫入excel文件,另一類是需要追加寫入。直接寫入excel的方式,可直接參考 easyexcel 的文檔,采用的是按照模板填充。

今天主要是分享追加寫入的方式,因為項目的原因,沒有使用數(shù)據(jù)庫,所以匯總數(shù)據(jù)時,需要把每次測試數(shù)據(jù)追加寫入的同一個 excel 文件中。

本文主要參考了easyexcel已存在的excel里追加數(shù)據(jù)(csdn) 和 easyexcel往已存在的excel文件里追加數(shù)據(jù)(cnblog)兩篇文章,并根據(jù)自己的需求進行了相應的修改。
DEMO 代碼如下:

private static void writeAppend(String fileName) {
    File file = new File("C:/Users/Administrator/Documents/Code/" + fileName);
    File tempFile = new File("C:/Users/Administrator/Documents/Code/temp.xlsx");
    if (file.exists()){
        // 第二次按照原有格式,不需要表頭,追加寫入
        EasyExcel.write(file, TestData.class).needHead(false).
                withTemplate(file).file(tempFile).sheet().doWrite(testData());
    }else {
        // 第一次寫入需要表頭
        EasyExcel.write(file,TestData.class).sheet().doWrite(testData());
    }

    if (tempFile.exists()){
        file.delete();
        tempFile.renameTo(file);
    }
}

實際效果如下圖
在這里插入圖片描述
需要注意:

  1. 追加寫入時,如果 write 方法不帶參數(shù),默認從第一列寫入,可能會導致和預想的結果有出入;
  2. 追加寫入時,后面的追加不需要寫入表頭,因此需要調(diào)用 needHead(false) 方法;
  3. 使用doWrite方法執(zhí)行寫入,使用完后會自動釋放資源,如果不釋放資源可能會導致后面的重命名失?。?/li>

原文鏈接:https://blog.csdn.net/Lincain/article/details/125707455

欄目分類
最近更新