Excel導入導出工具類


import cn.sucang.core.util.StrUtils;
import com.jiminy.delivery.annocation.Excel;
import com.jiminy.delivery.dto.ReturnResult;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Excel相關處理
 */
public class ExcelUtil<T> {

    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    public Class<T> clazz;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    /**
     * 用於將科學計數法式的數字轉換爲常規數字顯示,BigDecimal表示。<br>
     * 如:6.913084212242E12  轉換成:6940282300075
     *
     * @param obj as Object
     * @return
     */
    public static String decimal2string(Object obj) {
        BigDecimal big = null;
        if (obj == null) {
            return "";
        }
        if (obj instanceof Number) {
            big = new BigDecimal(((Number) obj).doubleValue());
        } else {
            return obj.toString();
        }
        return big == null ? "" : big.toPlainString();
    }

    public List<T> importExcel(String sheetName, InputStream input) throws Exception {
        List<T> list = new ArrayList<T>();

        Workbook workbook = WorkbookFactory.create(input);
        Sheet sheet = null;
        if (StrUtils.isEmpty(sheetName)) {
            sheet = workbook.getSheetAt(0);
        } else {
            sheet = workbook.getSheet(sheetName);
        }
        int rows = sheet.getPhysicalNumberOfRows();

        if (rows > 0) {
            // 有數據時才處理 得到類的所有field.
            Field[] allFields = clazz.getDeclaredFields();
            // 定義一個map用於存放列的序號和field.
            List<Field> fieldsMap = new ArrayList<>();
            for (int col = 0; col < allFields.length; col++) {
                Field field = allFields[col];
                // 將有註解的field存放到map中.
                if (field.isAnnotationPresent(Excel.class)) {
                    // 設置類的私有字段屬性可訪問.
                    field.setAccessible(true);
                    fieldsMap.add(field);
                }
            }
            for (int i = 1; i < rows; i++) {
                // 從第2行開始取數據,默認第一行是表頭.
                Row row = sheet.getRow(i);
                //獲取一行所有的單元格的數量
                int cellNum = sheet.getRow(0).getPhysicalNumberOfCells();
                T entity = null;
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) {
                        continue;
                    } else {
                        cell = row.getCell(j);
                    }

                    String c = null;
                    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                        c = decimal2string(cell.getNumericCellValue());
                    } else {
                        c = cell.getStringCellValue();
                    }
                    if (StringUtils.isEmpty(c)) {
                        continue;
                    }
                    c = replaceBlank(c);
                    // 如果不存在實例則新建.
                    entity = entity == null ? clazz.newInstance() : entity;
                    // 從map中得到對應列的field.
                    Field field = fieldsMap.get(j);
                    // 取得類型,並根據對象類型設置值.
                    Class<?> fieldType = field.getType();
//                    Class<?> fieldType = String.class;
                    if (String.class == fieldType) {
                        field.set(entity, String.valueOf(c));
                    } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
                        field.set(entity, Integer.parseInt(c));
                    } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
                        field.set(entity, Long.valueOf(c));
                    } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
                        field.set(entity, Float.valueOf(c));
                    } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
                        field.set(entity, Short.valueOf(c));
                    } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
                        field.set(entity, Double.valueOf(c));
                    } else if (Character.TYPE == fieldType) {
                        if ((c != null) && (c.length() > 0)) {
                            field.set(entity, Character.valueOf(c.charAt(0)));
                        }
                    } else if (java.util.Date.class == fieldType) {
                        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            cell.setCellValue(sdf.format(cell.getNumericCellValue()));
                            c = sdf.format(cell.getNumericCellValue());
                        } else {
                            c = cell.getStringCellValue();
                        }
                    } else if (BigDecimal.class == fieldType) {
                        c = cell.getStringCellValue();
                    }
                }
                if (entity != null) {
                    list.add(entity);
                }
            }
        }

        return list;
    }


    /**
     * 導出excel到網絡(直接將http)
     *
     * @param list
     * @param sheetName
     * @param response
     * @return
     */
    public void exportExcelToWeb(List<T> list, String sheetName, HttpServletResponse response) {
        // 告訴瀏覽器用什麼軟件可以打開此文件
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sheetName + ".xls", "utf-8"));
            this.exportExcel(list, sheetName, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void download(List<T> list, String sheetName, HttpServletResponse response) throws UnsupportedEncodingException {
        // 告訴瀏覽器用什麼軟件可以打開此文件
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String fileName = df.format(new Date()) + "導出數據";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            this.exportExcel(list, sheetName, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 導出excel到指定路徑
     *
     * @param list
     * @param sheetName
     * @param path
     * @return
     */
    public ReturnResult exportExcelToPath(List<T> list, String sheetName, String path) {
        ReturnResult returnResult = null;
        try {
            OutputStream out = new FileOutputStream(path);
            returnResult = this.exportExcel(list, sheetName, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnResult;
    }

    /**
     * 對list數據源將其裏面的數據導入到excel表單
     * <p>
     * 通過制定out,實現導出到磁盤/網絡
     *
     * @param sheetName 工作表的名稱
     */
    public ReturnResult exportExcel(List<T> list, String sheetName, OutputStream out) {
        // 得到所有定義字段
        Field[] allFields = clazz.getDeclaredFields();
        List<Field> fields = new ArrayList<Field>();
        // 得到所有field並存放到一個list中.
        for (Field field : allFields) {
            if (field.isAnnotationPresent(Excel.class)) {
                fields.add(field);
            }
        }

        // 產生工作薄對象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // excel2003中每個sheet中最多有65536行
        int sheetSize = 65536;
        // 取出一共有多少個sheet.
        double sheetNo = Math.ceil(list.size() / sheetSize);
        for (int index = 0; index <= sheetNo; index++) {
            // 產生工作表對象
            HSSFSheet sheet = workbook.createSheet();
            if (sheetNo == 0) {
                workbook.setSheetName(index, sheetName);
            } else {
                // 設置工作表的名稱.
                workbook.setSheetName(index, sheetName + index);
            }
            HSSFRow row;
            HSSFCell cell; // 產生單元格

            // 產生一行
            row = sheet.createRow(0);
            // 寫入各個字段的列頭名稱
            for (int i = 0; i < fields.size(); i++) {
                Field field = fields.get(i);
                Excel attr = field.getAnnotation(Excel.class);
                // 創建列
                cell = row.createCell(i);
                // 設置列中寫入內容爲String類型
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                HSSFCellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
                if (attr.name().indexOf("注:") >= 0) {
                    HSSFFont font = workbook.createFont();
                    font.setColor(HSSFFont.COLOR_RED);
                    cellStyle.setFont(font);
                    cellStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
                    sheet.setColumnWidth(i, 6000);
                } else {
                    HSSFFont font = workbook.createFont();
                    // 粗體顯示
                    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                    // 選擇需要用到的字體格式
                    cellStyle.setFont(font);
                    // 設置列寬
                    sheet.setColumnWidth(i, 3766);
                }
                cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                cellStyle.setWrapText(true);
                cell.setCellStyle(cellStyle);

                // 寫入列名
                cell.setCellValue(attr.name());

                // 如果設置了提示信息則鼠標放上去提示.
                if (!StringUtils.isEmpty(attr.prompt())) {
                    // 這裏默認設了2-101列提示.
                    setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, i, i);
                }
                // 如果設置了combo屬性則本列只能選擇不能輸入
                if (attr.combo().length > 0) {
                    // 這裏默認設了2-101列只能選擇不能輸入.
                    setHSSFValidation(sheet, attr.combo(), 1, 100, i, i);
                }
            }

            int startNo = index * sheetSize;
            int endNo = Math.min(startNo + sheetSize, list.size());
            // 寫入各條記錄,每條記錄對應excel表中的一行
            HSSFCellStyle cs = workbook.createCellStyle();
            cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
            for (int i = startNo; i < endNo; i++) {
                row = sheet.createRow(i + 1 - startNo);
                // 得到導出對象.
                T vo = (T) list.get(i);
                for (int j = 0; j < fields.size(); j++) {
                    // 獲得field.
                    Field field = fields.get(j);
                    // 設置實體類私有屬性可訪問
                    field.setAccessible(true);
                    Excel attr = field.getAnnotation(Excel.class);
                    try {
                        // 根據Excel中設置情況決定是否導出,有些情況需要保持爲空,希望用戶填寫這一列.
                        if (attr.isExport()) {
                            // 創建cell
                            cell = row.createCell(j);
                            cell.setCellStyle(cs);
                            try {
                                if (String.valueOf(field.get(vo)).length() > 10) {
                                    throw new Exception("長度超過10位就不用轉數字了");
                                }
                                // 如果可以轉成數字則導出爲數字類型
                                BigDecimal bc = new BigDecimal(String.valueOf(field.get(vo)));
                                cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                cell.setCellValue(bc.doubleValue());
                            } catch (Exception e) {
                                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                                if (vo == null) {
                                    // 如果數據存在就填入,不存在填入空格.
                                    cell.setCellValue("");
                                } else {
                                    // 如果數據存在就填入,不存在填入空格.
                                    cell.setCellValue(field.get(vo) == null ? "" : String.valueOf(field.get(vo)));
                                }

                            }
                        }
                    } catch (Exception e) {
                        log.error("導出Excel失敗{}", e.getMessage());
                    }
                }
            }
        }
        try {
            String filename = encodingFilename(sheetName);
            //OutputStream out = new FileOutputStream(getfile() + filename);
            workbook.write(out);
            out.close();
            ReturnResult returnResult = new ReturnResult();
            returnResult.setMsg("filename");
            returnResult.setCode(1);
            return returnResult;
        } catch (Exception e) {
            log.error("關閉flush失敗{}", e.getMessage());
            ReturnResult returnResult = new ReturnResult();
            returnResult.setMsg("導出Excel失敗,請聯繫網站管理員!");
            returnResult.setCode(-1);
            return returnResult;
        }
    }

    /**
     * 設置單元格上提示
     *
     * @param sheet         要設置的sheet.
     * @param promptTitle   標題
     * @param promptContent 內容
     * @param firstRow      開始行
     * @param endRow        結束行
     * @param firstCol      開始列
     * @param endCol        結束列
     * @return 設置好的sheet.
     */
    public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow,
                                          int endRow, int firstCol, int endCol) {
        // 構造constraint對象
        DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("DD1");
        // 四個參數分別是:起始行、終止行、起始列、終止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        // 數據有效性對象
        HSSFDataValidation dataValidationView = new HSSFDataValidation(regions, constraint);
        dataValidationView.createPromptBox(promptTitle, promptContent);
        sheet.addValidationData(dataValidationView);
        return sheet;
    }

    /**
     * 設置某些列的值只能輸入預製的數據,顯示下拉框.
     *
     * @param sheet    要設置的sheet.
     * @param textlist 下拉框顯示的內容
     * @param firstRow 開始行
     * @param endRow   結束行
     * @param firstCol 開始列
     * @param endCol   結束列
     * @return 設置好的sheet.
     */
    public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow,
                                              int firstCol, int endCol) {
        // 加載下拉列表內容
        DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);
        // 設置數據有效性加載在哪個單元格上,四個參數分別是:起始行、終止行、起始列、終止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        // 數據有效性對象
        HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint);
        sheet.addValidationData(dataValidationList);
        return sheet;
    }

    /**
     * 編碼文件名
     */
    public String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xls";
        return filename;
    }

    public String getfile() throws FileNotFoundException {
        return ResourceUtils.getURL("classpath:").getPath() + "static/file/";
    }

    public String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
}

/**
* 返回結果類
*/

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class ReturnResult implements Serializable {

	private static final long serialVersionUID = 6816265515135254415L;
	public ReturnResult(){
		
	}
	public ReturnResult(int c, String m){
		this.code = c;
		this.msg = m;
	}
	public ReturnResult(int c, String m, Map<String, Object> dataMap){
		this(c, m);
		this.data = dataMap;
	}
	private Map<String, Object> data;
	protected int code = 0;
	protected String msg = "";
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public Map<String, Object> getData() {
		return data;
	}
	public void setData(Map<String, Object> data) {
		this.data = data;
	}
	public void putAll(Map<String, Object> data){
		if(this.data == null) this.data = new HashMap<String, Object>();
		this.data.putAll(data);
	}
	public void put(String key, Object value){
		if(this.data == null) this.data = new HashMap<String, Object>();
		this.data.put(key, value);
	}
}


/**
* 工具註解
*/

import java.lang.annotation.*;

/**
 * 自定義導出Excel數據註解
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Excel
{
    /**
     * 導出到Excel中的名字.
     */
    public abstract String name();

    /**
     * 提示信息
     */
    public abstract String prompt() default "";

    /**
     * 設置只能選擇不能輸入的列內容.
     */
    public abstract String[] combo() default {};

    /**
     * 是否導出數據,應對需求:有時我們需要導出一份模板,這是標題需要但內容需要用戶手工填寫.
     */
    public abstract boolean isExport() default true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章