Excel導入導出神器(Java)

連接

爲何使用AutoExcel?

Excel導入導出在軟件開發中很是常見,只要你接觸過開發,就必定會遇到。相信不少人會跟我同樣選擇用Apache POI來完成這項工做,在感覺到POI功能強大的同時,個人團隊也遇到了如下問題:java

  1. 直接使用POI操做Excel將產生大量硬編碼,你會在編碼中寫死行索引和列索引
  2. 大量不可複用的格式控制編碼,如背景色、對齊方式、單元格樣式等
  3. 實施顧問明明提供了現成的模板,卻還要開發用代碼實現一遍,開發效率低下
  4. 模板調整時不得不動用開發資源
  5. 簡單的導出也須要寫特定的代碼

AutoExcel解決了上述問題,它很是簡單,只須要少許的代碼便可完成複雜的導入導出;使用它時,程序員對導入導出無感,即不須要直接操做POI;與此同時,實施顧問提供的Excel便是導入導出模板,除非新增數據源或字段,不然模板更新不須要動用開發資源。git

AutoExcel並無對POI進行太重的封裝,而是充分利用了Excel自己具備的特性——名稱管理器,經過一些小技巧,將單元格與數據源產生映射,從而解耦程序員與POI,避免產生硬編碼,讓導入導出工做變得愉快而再也不是枯燥乏味。程序員

功能預覽

導出前 導出後
image image
image image
image image
image image

實現以上導出只須要編寫如下少許代碼(你須要額外的代碼來準備數據源,例如從數據庫中獲取)github

List<TemplateExportPara> paras = new ArrayList<>();
paras.add(new TemplateExportPara("BusinessUnit", DataGenerator.genBusinessUnit()));
paras.add(new TemplateExportPara("Contract", DataGenerator.genContracts()));
paras.add(new TemplateExportPara("Project", DataGenerator.genProjects()));

List<Product> products = DataGenerator.genProducts();
TemplateExportPara para3 = new TemplateExportPara("Product", products);
para3.setInserted(true);
paras.add(para3);

TemplateExportPara para5 = new TemplateExportPara("Product2", products);
para5.setDataDirection(DataDirection.Right);
paras.add(para5);

ExcelSetting excelSetting = new ExcelSetting();
excelSetting.setRemovedSheets(Arrays.asList("will be removed"));

AutoExcel.save(this.getClass().getResource("/template/Common.xlsx").getPath(),
               this.getClass().getResource("/").getPath() + "ExportWithTemplate.xlsx",
               paras,
               excelSetting);

認識模板

要實現以上導出,首先須要完成模板的製做。一些報表製做工具如微軟的RDL,你會在RDL中製做好導出模型,而後結合代碼將數據導出到Excel。這個過程,RDL僅僅起到中介做用,意味着每次有新的導出任務,都得先製做一個導出模型。在AutoExcel中,Excel即模板,若是你的Excel來源是實施顧問,極可能這個Excel已經設定好數據格式、單元格樣式等,就等着你往上填數據,既然如此,何不就將這份Excel做爲咱們的導出模板,咱們要作的,僅僅是在其中加入咱們的東西而已。數據庫

名稱管理器

Excel中的名稱管理器,這個被大多數人忽視的功能,卻成爲AutoExcel中鏈接數據源與單元格的橋樑。你能夠經過點擊菜單公式->名稱管理器來打開名稱管理器,其中每個名稱都對應Excel中的某個具體位置,能夠是一個區域,也能夠是一個單元格,固然,在這裏,咱們定義的名稱都指向單元格。所以能夠這麼理解,名稱管理器就是用來給單元格命名的。正是由於單元格有了名字,咱們才能實現給單元格自動賦值而無需個性化的代碼。ide

image

爲單元格定義了名稱以後,當你再次點擊該單元格,會發現左上角的位置顯示了你剛纔定義的名稱工具

image

除了在名稱管理器中新增名稱,還有一種方式更加直觀快捷。點擊你想要命名的單元格,而後直接在左上角輸入名稱,最後按Entry鍵便可。推薦使用這種方式建立名稱。單元測試

image

名稱規則

因爲單元格名稱決定了何種數據按什麼方式進行填充,所以必須按如下規則進行命名:測試

  1. 數據源名稱.字段名稱[.合計類型],用於填充普通字段或普通字段的合計值,如:product.SaleArea.sum
  2. 數據源名稱.Formula.xxxx,用於填充公式,如:product.Formula.1
  3. 數據源名稱.RowNo,用於填充行號,如:product.RowNo

全部名稱均不區分大小寫,如下會根據具體場景分別進行介紹ui

導出

基礎對象

image

如圖所示,批註中註明了每一個單元格的名稱,按照數據源名稱.字段名稱的規則書寫

Java代碼:

String templatePath = this.getClass().getResource("/template/Common.xlsx").getPath();
String outputPath = this.getClass().getResource("/").getPath() + "ExportWithTemplate.xlsx";
//DataGenerator.genBusinessUnit()用於生成demo數據
TemplateExportPara para = new TemplateExportPara("BusinessUnit", DataGenerator.genBusinessUnit());
AutoExcel.save(templatePath, outputPath, para);

單表

image

若是你想導出的是一個列表數據,你只須要按照基礎對象的書寫規則進行命名便可。固然,列表數據導出每每比基礎對象複雜,好比,你可能須要一列行號,而又不想在代碼中作特殊處理,這時候你可使用數據源名稱.RowNo,將工做交給AutoExcel來處理。注意,RowNo是內置字段,若是數據源中包含此字段,將會被覆蓋。

還有一種狀況很是常見,你有一個帶公式的單元格在表格中,如:=E6+F6,你但願下一行的單元格被賦值=E7+F7,這時你應該使用數據源名稱.Formula.xxxx,你可使用任何你喜歡的公式,AutoExcel最終都會幫你自動填充。xxxx的部分你能夠隨便書寫,只要保證名稱惟一便可。Formula一樣是內置字段。

Java代碼:

String templatePath = this.getClass().getResource("/template/Common.xlsx").getPath();
String outputPath = this.getClass().getResource("/").getPath() + "ExportWithTemplate.xlsx";
//DataGenerator.genContracts()用於生成demo數據
TemplateExportPara para = new TemplateExportPara("Contract", DataGenerator.genContracts());
AutoExcel.save(templatePath, outputPath, para);

多表

image

在一個Sheet中導出多個表格,若是你有這樣的需求,請在代碼中將不是處於最下面的表格的導出參數設置爲:setInserted(true),如上圖,products對應的導出參數para應作以下設置:para.setInserted(true)。要知道,AutoExcel是不理會數據導出是否有足夠空間的,它只會一個勁地輸出,因此當你的模板空間不夠時,你須要告訴AutoExcel,以後AutoExcel會在導出前騰出足夠的空間來容納你的數據。

這裏引入了新的命名規則:數據源名稱.字段名稱.合計類型,用於對指定字段進行合計,目前支持兩種合計類型:Sum和Avg。

Java代碼:

String templatePath = this.getClass().getResource("/template/Common.xlsx").getPath();
String outputPath = this.getClass().getResource("/").getPath() + "ExportWithTemplate.xlsx";
List<TemplateExportPara> paras = new ArrayList<>();
//DataGenerator.genProjects()用於生成demo數據
paras.add(new TemplateExportPara("Project", DataGenerator.genProjects()));

//DataGenerator.genProducts()用於生成demo數據
TemplateExportPara para = new TemplateExportPara("Product", DataGenerator.genProducts());
para.setInserted(true);  //導出空間不夠時需設置
paras.add(para);

AutoExcel.save(templatePath, outputPath, paras);

向右填充

image

若是你須要將數據向右而不是向下填充,你只須要使用setDataDirection(DataDirection.Right)便可。

Java代碼:

String templatePath = this.getClass().getResource("/template/Common.xlsx").getPath();
String outputPath = this.getClass().getResource("/").getPath() + "ExportWithTemplate.xlsx";
TemplateExportPara para = new TemplateExportPara("Product2", DataGenerator.genProducts());
para.setDataDirection(DataDirection.Right);  //向右填充
AutoExcel.save(templatePath, outputPath, para);

直接導出

直接導出,即導出過程不須要藉助模板,適用於集成到後臺系統的通用導出功能中,代碼很是簡單

String outputPath = this.getClass().getResource("/").getPath() + "Export.xlsx";
DirectExportPara para = new DirectExportPara(DataGenerator.genProjects());
AutoExcel.save(outputPath, para);

效果:

image

固然,你並不會喜歡這樣的標題和標題順序,所以,你須要藉助FieldSetting來讓你的標題可讀且按照你喜歡的順序來展示。

List<FieldSetting> fieldSettings = new ArrayList<FieldSetting>() {{
    add(new FieldSetting("projName", "Project Name"));
    add(new FieldSetting("basalArea", "Basal Area"));
    add(new FieldSetting("buildingArea", "Building Area"));
    add(new FieldSetting("insideArea", "Inside Area"));
    add(new FieldSetting("availableArea", "Available Area"));
    add(new FieldSetting("availablePrice", "Available Price"));
    add(new FieldSetting("availableAmount", "Available Amount"));
}};
String outputPath = this.getClass().getResource("/").getPath() + "Export.xlsx";
DirectExportPara para = new DirectExportPara(DataGenerator.genProjects(), "Projects", fieldSettings);
AutoExcel.save(outputPath, para);

最終效果:

image

自定義操做

AutoExcel致力於處理導入導出的通用場景,若是有個性化的需求,你應該取回Workbook的控制權,根據你的需求進行個性化處理。save方法提供了兩個Consumer,其中actionAhead會在導出操做開始以前被調用,actionBehind會在導出完成以後被調用,你徹底能夠經過這兩個Consumer來添加你想要的功能。

String templatePath = this.getClass().getResource("/template/Common.xlsx").getPath();
String outputPath = this.getClass().getResource("/").getPath() + "ExportWithTemplate.xlsx";
List<TemplateExportPara> paras = new ArrayList<>();
paras.add(new TemplateExportPara("BusinessUnit", DataGenerator.genBusinessUnit()));
Consumer<Workbook> actionAhead = Workbook -> {
    //作任何你想作的事情
};        
Consumer<Workbook> actionBehind = workbook -> {
    //作任何你想作的事情
};
AutoExcel.save(templatePath, outputPath, paras, actionAhead, actionBehind);

導入

相較於導出,導入具備如下特色:

  1. 僅支持一種名稱規則:數據源名稱.字段名稱
  2. 暫不支持一個Sheet有多個表的狀況
  3. 默認數據讀取方向(DataDirection)爲null,即讀取基礎對象,如需讀取列表,需指明讀取方向爲Down,暫不支持Right方向的讀取。

Java代碼:

List<ImportPara> importParas = new ArrayList<ImportPara>() {{
    add(new ImportPara("BusinessUnit"));
    add(new ImportPara("Contract", DataDirection.Down));
    add(new ImportPara("Project", DataDirection.Down));
    //add(new ImportPara("Product", DataDirection.Down));   暫不支持
}};
String fileName = this.getClass().getResource("/").getPath() + "ExportWithTemplate.xlsx";
HashMap<String, List<HashMap<String, Object>>> datas = AutoExcel.read(fileName, importParas);

運行示例代碼

完整的示例代碼請前往單元測試查看

GitHub地址

image

相關文章
相關標籤/搜索