Java工具类--List带出excel

package com.zp.prod;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * 此工具类完成任何一个对象数组直接保存成excel
 * 
 * @author eagle
 *
 */
public class PrintExcelTool {
    private OutputStream out;

    private HSSFWorkbook workbook;

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        PrintExcelTool p = new PrintExcelTool();
        User user = new User();
        user.setUsername("fyl");
        user.setPassword("111");
        User user2 = new User();
        user2.setUsername("mm");
        user2.setPassword("222");
        List list = new ArrayList<>();
        list.add(user);
        list.add(user2);
        p.export(list, User.class, "E:\\books\\user.xls");

    }

    /**
     * 导出方法
     * 
     * @param list 次数组为clazz实例的数组
     * @param clazz 某对象类对象
     * @param outputPath 导出目录含文件名
     * @throws Exception
     */
    public  void export(List list, Class clazz, String outputPath)
            throws Exception {
        // 获取页签名
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String time = df.format(new Date());
        String sheetName = clazz.getSimpleName() + time;

        try {
            File file = Paths.get(outputPath).toFile();

            if (file.exists()) {
                POIFSFileSystem ps = new POIFSFileSystem(
                        new FileInputStream(file)); // 使用POI提供的方法得到excel的信息
                workbook = new HSSFWorkbook(ps);
            }
            else {
                workbook = new HSSFWorkbook();
            }
            out = new FileOutputStream(file);

            HSSFSheet sheet = workbook.getSheet(sheetName);
            if (sheet != null) {
                for (int i = 1; i <= list.size(); i++) {

                    HSSFRow row2Replace = sheet.getRow(i);
                    if (row2Replace == null)
                        row2Replace = sheet.createRow(i);

                    for (int j = 0; j < 2; j++) {
                        row2Replace.removeCell(row2Replace.getCell(j));
                    }
                }
            }
            else {
                sheet = workbook.createSheet(sheetName);
            }

            // sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 获取列头样式对象
            HSSFCellStyle style = this.getStyle(workbook); // 单元格样式对象

            String[] header = getColumnHeader(clazz);
            // 定义所需列数
            int columnNum = header.length;
            HSSFRow rowRowName = sheet.createRow(0); // 在索引2的位置创建行(最顶端的行开始的第二行)

            // 将列头设置到sheet的单元格中
            for (int n = 0; n < columnNum; n++) {
                HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
                HSSFRichTextString text = new HSSFRichTextString(header[n]);
                cellRowName.setCellValue(text); // 设置列头单元格的值
                cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
            }

            // 将查询出的数据设置到sheet对应的单元格中
            for (int i = 0; i < list.size(); i++) {

                Map obj = getFieldValueMap(clazz, list.get(i));// 遍历每个对象
                HSSFRow row = sheet.createRow(i + 1);// 创建所需的行数

                for (int j = 0; j < header.length; j++) {
                    HSSFCell cell = row.createCell(j,
                            HSSFCell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(obj.get(header[j]) == null ? ""
                            : obj.get(header[j]).toString());
                    cell.setCellStyle(style); // 设置单元格样式
                }
            }
            // 让列宽随着导出的列长自动适应
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    // 当前行未被使用过
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    }
                    else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell
                                .getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            int length = currentCell.getStringCellValue()
                                    .getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
                }
                else {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
                }
            }

            if (workbook != null) {
                workbook.write(out);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            workbook.close();
            out.close();
        }
    }

    protected  Map getFieldValueMap(Class clazz,
            T entity) {
        // key是属性名,value是对应值
        Map fieldValueMap = new HashMap();

        while (clazz != Object.class) {
            try {
                // 获取当前加载的实体类中所有属性(字段)
                Field[] fields = clazz.getDeclaredFields();

                for (int i = 0; i < fields.length; i++) {
                    Field f = fields[i];
                    String key = f.getName();// 属性名
                    Object value = null;// 属性值
                    if (!"serialVersionUID".equals(key)) {// 忽略序列化版本ID号
                        f.setAccessible(true);// 取消Java语言访问检查
                        try {
                            value = f.get(entity);
                        }
                        catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        }
                        catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                        fieldValueMap.put(key, value);
                    }
                }
                clazz = (Class) clazz.getSuperclass();
            }
            catch (Exception ex) {

            }
        }

        return fieldValueMap;
    }

    public  String[] getColumnHeader(Class clazz) {
        List headers = new ArrayList();

        while (clazz != Object.class) {
            try {
                Field[] fs = clazz.getDeclaredFields();
                for (Field f : fs) {
                    headers.add(f.getName());
                }
                clazz = (Class) clazz.getSuperclass();
            }
            catch (Exception e) {
                // 这里甚么都不能抛出去。
                // 如果这里的异常打印或者往外抛,则就不会进入
            }
        }

        return headers.toArray(new String[0]);

    }

    /*
     * 列头单元格样式
     */
    public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 11);
        // 字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }

    /*
     * 列数据信息单元格样式
     */
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        // font.setFontHeightInPoints((short)10);
        // 字体加粗
        // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }
}

你可能感兴趣的:(Java工具类)