JFinalOA導出Excel

緒論

最近有同事反映,使用OA系統過程中需要使用導出功能,說是有時間讓我做一下,所以今天抽時間做一個,又想到導出功能以後是一個常用的功能,最好不要寫的太死,能根據參數進行一些配置就好了,當需要其它導出內容時,能減少自己的開發時間。

代碼

ToolPoi.java

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Record;
import com.pointlion.sys.mvc.common.model.ZProject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.util.*;

/**
 * poi工具類
 * Created by 陽 on 2019/2/20.
 */
public class ToolPoi{
    private String fileName;
    private String sheetName;
    private List<Map<String, String>> headName;
    private List<Record> recordData;

    public ToolPoi(int fileNum, int sheetNum, int headNum){
        createFileName(fileNum);
        createSheetName(sheetNum);
        createHeadName(headNum);
    }

    /**
     * 創建導出excel的文件名稱
     * @param num
     */
    private void createFileName(int num){
        String path = PathKit.getWebRootPath() + File.separator;
        switch (num) {
            case 0:
                fileName = "項目臺賬";
                break;
            default:
                fileName = "未知";
        }
        fileName = path + fileName + "_" + com.pointlion.sys.mvc.common.utils.DateUtil.dateToString(new Date(), 9) + ".xls";
    }

    /**
     * 創建sheet名稱
     * @param num
     */
    private void createSheetName(int num){
        switch (num) {
            case 0:
                sheetName = "項目臺賬";
                break;
            default:
                sheetName = "未知";
        }
    }

    /**
     * 創建表頭模板:key數據庫字段,value表頭名稱
     * 最好可以利用Java的反射機制把數據庫數據寫入excel
     * @param num
     */
    public void createHeadName(int num){
        headName = new ArrayList<>();
        Map<String, String> map;
        switch (num) {
            case 0:
                map = new HashMap<>();
                map.put("headName", "項目編號");
                map.put("columnName", "pro_no");
                headName.add(map);
                map = new HashMap<>();
                map.put("headName", "項目名稱");
                map.put("columnName", "pro_name");
                headName.add(map);
                map = new HashMap<>();
                map.put("headName", "項目類型");
                map.put("columnName", "p_type");
                headName.add(map);
                map = new HashMap<>();
                map.put("headName", "客戶經理");
                map.put("columnName", "user_name");
                headName.add(map);
                map = new HashMap<>();
                map.put("headName", "申請日期");
                map.put("columnName", "start_time");
                headName.add(map);
                map = new HashMap<>();
                map.put("headName", "項目狀態");
                map.put("columnName", "pro_flag");
                headName.add(map);
                break;
            default:
        }
    }

    /**
     * 獲取想要寫入excel的數據
     * @param dataType  數據類型
     * @param parameter 參數
     */
    public void queryData(int dataType, String... parameter){
        switch (dataType) {
            case 0:
                recordData = ZProject.dao.queryExcelData(parameter[0]);
                break;
            default:
                recordData = new ArrayList<>();
        }
    }

    /**
     * 寫入excel數據
     * @return
     */
    public File writeExcel(){
        File file = new File(fileName);
        // 創建工作薄
        Workbook workbook = new HSSFWorkbook();
        // 生成一個sheet頁面
        Sheet sheet = workbook.createSheet(sheetName);
        // 設置表格默認列寬度爲20個字節
        sheet.setDefaultColumnWidth(20);
        sheet.setDefaultRowHeightInPoints(24);
        // 產生表格標題行
        Row row = sheet.createRow(0);
        // 生成一個表格標題行樣式
        CellStyle style = workbook.createCellStyle();
        // 設置這些樣式
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成一個字體
        Font font = workbook.createFont();
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        // 把字體應用到當前的樣式
        style.setFont(font);

        // 寫入表頭
        for (int i = 0; headName != null && i < headName.size(); i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(style);
            RichTextString text = new HSSFRichTextString(headName.get(i).get("headName"));
            cell.setCellValue(text);
        }

        // 寫入數據
        for (int j = 0; recordData != null && j < recordData.size(); j++) {
            row = sheet.createRow(j + 1);
            Record record = recordData.get(j);
            for (int k = 0; k < headName.size(); k++) {
                Cell cell = row.createCell(k);
                cell.setCellValue((String)record.get(headName.get(k).get("columnName")));
            }
        }

        try {
            OutputStream outputStream = new FileOutputStream(file);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}

ExportController.java

import com.jfinal.aop.Before;
import com.pointlion.sys.interceptor.MainPageTitleInterceptor;
import com.pointlion.sys.mvc.common.base.BaseController;
import com.pointlion.sys.mvc.zUtils.ToolPoi;

/**
 * 導出表格
 * Created by 陽 on 2019/2/20.
 */
@Before(MainPageTitleInterceptor.class)
public class ExportController extends BaseController {

    /**
     * 項目臺賬導出
     */
    public void exportProjectExcel(){
        String year = getPara("year");
        ToolPoi toolPoi = new ToolPoi(0, 0, 0);
        toolPoi.queryData(0, year);
        renderFile(toolPoi.writeExcel());
    }
}

雖說可以實現下載功能,但是會在項目根目錄產生文件。

(若有什麼錯誤,請留言指正,3Q)

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