java基於poi匯出excel透視表程式碼例項
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了java基於poi匯出excel透視表程式碼例項,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
從前,我是一個前端程式猿,懷著對打通任(前)督(後)二(開)脈(發)的夢想轉了後端,自學兩禮拜java+spring全家桶,直接上專案實戰。最近接到一需求:將業務資料匯出一張透視表。
需求開發完成已近有一段時間了,甲方的大爺大媽,爺爺奶奶們也都用的很開心,我也很開心,於是就心想咱學了也不能白學,所以寫下這篇隨筆。
先看下用easypoi+POI匯出的excel效果圖(easypoi用來匯出sheet1資料來源,poi用來sheet0透視表):
圖中的excel分為兩個sheet,sheet1是資料來源,sheet0是根據sheet的資料生成的透視表。程式碼如下:
// 利用esaypoi生成excel資料,即sheet1裡面的資料 Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null,"sheet1",ExcelType.XSSF),pojoClass,list); Sheet sheet1 = workbook.getSheetAt(0); sheet1.setDefaultColumnWidth(50 * 256); sheet1.setDefaultRowHeight((short)(2 * 256)); // 建立資料透視sheet XSSFSheet pivotSheet = (XSSFSheet )workbook.createSheet(); pivotSheet.setDefaultColumnWidth(50 * 256); // 獲取資料sheet的總行數 int num = sheet1.getLastRowNum(); // 資料透視表資料來源的起點單元格位置 CellReference topLeft = new CellReference("A1"); // 資料透視表資料來源的終點單元格位置 CellReference botRight = new CellReference(("M"+num)); // 資料透視表生產的起點單元格位置 CellReference ptStartCell = new CellReference("A1"); AreaReference areaR = new AreaReference(topLeft,botRight); XSSFPivotTable pivotTable = pivotSheet.createPivotTable(areaR,ptStartCell,sheet1); // 新增行標籤 pivotTable.addRowLabel(4); // 部門 pivotTable.addRowLabel(1); // 科目 pivotTable.addRowLabel(0); // 借貸方向 pivotTable.addRowLabel(11); // 單據編號 pivotTable.addRowLabel(12); // 憑證編號 pivotTable.addRowLabel(9); // 付款編碼 pivotTable.addRowLabel(10); // 付款時間 pivotTable.addColumnLabel(DataConsolidateFunction.SUM,3,"分錄金額"); // 將透視表的列以表格的樣式顯示 這個地方弄了好久 int count = 13; // count為資料來源的列的數量 for (int i = 0; i < count; i++) { CTPivotField ctPivotField = pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(i); ctPivotField.setOutline(false); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。