excel文件下载工具分享

本文分享了一个使用Java反射机制的Excel文件下载工具,通过一个公共API调用和组装不同参数,实现管理系统中各菜单下Excel文件的灵活下载。代码示例展示了如何封装Excel文件的标题、行读取方法等,利用反射机制处理不同格式的下载需求。

        好久没和大家分享点东西了,今天就和大家分享一个excel文件下载工具,项目中有很多下载功能,尤其管理系统,每个菜单下都有下载功能,如果没有一个公共的工具类,就会乱套,维护起来也很吃力(不同菜单下的下载因为excel格式的不同导致写法不同),那么我们用什么方法能够使得通过一个公共的API调用+组装各自不同的参数就可以实现不同菜单下的下载功能呢?我想你也该想到了,那就是java反射机制。不多说了,我先大体说下我的代码的用法:

涉及到的几个方法:BaseInf,fillFieldAndTitle,initParamCondition,downloadTransferProList

BaseInf:该实体类封装了excel文件的第一行标题,行读取方法,转义列表,行尾统计,数据处理类,数据处理方法

fillFieldAndTitle:组装BaseInf数据

downloadTransferProList:excel文件下载的方法,读取前面组装的java反射用的数据,利用ExcelUtil中的java反射程序实现下载

自己看去吧,很简单的

具体的代码实现:

import java.lang.reflect.Method;

import java.util.Map;

/**

 * 列开头信息和结尾信息

 */

public class BaseInf {

/*

* 标题

*/

private String titleName;

/*

* 行读取方法

*/

private String columMethod;

/*

* 转义列表

*/

private Map<String, String> map;

/*

* 行尾统计

*/

private String count;

/**

* 数据处理类

*/

private Class<?> clazz;

/**

* 数据处理方法

*/

private Method method;

/**

* 全成员构造方法

* @param titleName

* @param columMethod

* @param map

* @param count

* @param clazz

* @param method

*/

public BaseInf(String titleName, String columMethod, Map<String, String> map, String count, Class<?> clazz,

Method method) {

super();

this.titleName = titleName;

this.columMethod = columMethod;

this.map = map;

this.count = count;

this.clazz = clazz;

this.method = method;

}

public BaseInf(String titleName, String columMethod, Class<?> clazz, Method method) {

super();

this.titleName = titleName;

this.columMethod = columMethod;

this.clazz = clazz;

this.method = method;

}

public BaseInf(String titleName, String columMethod,String count, Class<?> clazz, Method method) {

super();

this.titleName = titleName;

this.columMethod = columMethod;

this.clazz = clazz;

this.method = method;

this.count = count;

}

/**

* 有转义列表 有统计的构造方法

* @param titleName

* @param columMethod

* @param map

* @param count

*/

public BaseInf(String titleName, String columMethod, Map<String, String> map, String count) {

super();

this.titleName = titleName;

this.columMethod = columMethod;

this.map = map;

this.count = count;

}

/**

* 有转义列表构造方法

* @param titleName

*            标题

* @param columMethod

*            获取方法

* @param map

*            转义列表

*/

public BaseInf(String titleName, String columMethod, Map<String, String> map) {

super();

this.titleName = titleName;

this.columMethod = columMethod;

this.map = map;

this.count = null;

}

/**

* 无转义列表 有合计数据

* @param titleName 标题

* @param columMethod 读取方法列表

* @param count 合计值

*/

public BaseInf(String titleName, String columMethod, String count) {

super();

this.titleName = titleName;

this.columMethod = columMethod;

this.map = null;

this.count = count;

}

/**

* 无转义列表无统计构造方法

* @param titleName

*            标题

* @param columMethod

*            获取方法

*/

public BaseInf(String titleName, String columMethod) {

super();

this.titleName = titleName;

this.columMethod = columMethod;

this.map = null;

this.count = null;

}

public String getTitleName() {

return titleName;

}

public String getColumMethod() {

return columMethod;

}

public Map<String, String> getMap() {

return map;

}

public String getCount() {

return count;

}

public Class<?> getClazz() {

return clazz;

}

public Method getMethod() {

return method;

}

}

/**

* 下载接口

*/

public ActionForward downloadTransferProList(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

TtransferParam transferParam = new TtransferParam();

List<TtransferInfo> listinfo = null;

SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");

String startAppTime = sdf2.format(new Date());

// 开始时间

String fileName = "excel文件名称" + startAppTime;// 文件名称

try {

/*

* 初始化查询条件参数

*/

transferParam = transferService.initParamCondition(request);

/*

* 根据查询条件查询信结果

*/

listinfo = (List<TtransferInfo>) transferService.getSettleManageList(transferParam);

List<BaseInf> baseInfList = transferService.fillFieldAndTitle(listinfo);// 获取封装excel中单元格属性名和获取值的对象的集合

/*

* 调用ExcelUtil工具类实现excel下载功能

*/

if (response != null && listinfo != null) {

org.apache.poi.ss.usermodel.Workbook workbook = ExcelUtil.createWorkbook(2007, "结算提现划款查询", baseInfList,

listinfo,true);

ExcelUtil.workbook2InputStream(response, workbook, fileName, ".xls");

return null;

}

} catch (Exception e) {

String memo = "下载失败,请稍后再试 ···";

log.info("异常:{} ", memo, e);

request.setAttribute(ReturnConstant.MEMO, memo);

return mapping.findForward(ReturnConstant.ERROR);

}

return null;

}

/*封装查询参数*/

public TtransferParam initParamCondition(HttpServletRequest request) throws ParseException {

String type = request.getParameter("type");

TtransferParam transferParam = new TtransferParam();

transferParam.setMakeExcel(true);

// 参数判断

if (type != null ) {

transferParam.setType(Integer.parseInt(type));

} else {

type = "";

}

// 银行ID

if (StringUtil.isNotEmpty(bankId)) {

transferParam.setBankId(bankId);

} else {

bankId = "";

}

transferParam.setSTATE(1); // 状态

return transferParam;

}

public List<BaseInf> fillFieldAndTitle(List<TtransferInfo> list) throws NoSuchMethodException, SecurityException {

// 金额

long ableSumAmt = 0L;

// 手续费

long stlSumFee = 0L;

for (TtransferInfo tranfer : list) {

ableSumAmt += (tranfer.getT0_USEABLE_AMT() == null ? 0 : tranfer.getT0_USEABLE_AMT());

stlSumFee += (tranfer.getSTL_FEE() == null ? 0 : tranfer.getSTL_FEE());

}

List<BaseInf> baseInfList = new ArrayList<BaseInf>();

BaseInf baseInf = new BaseInf("批次号", "getID");

baseInfList.add(baseInf);

baseInf = new BaseInf("金额(元)", "getT0UserableAmt",Tools.formatAmt(ableSumAmt));

baseInfList.add(baseInf);

baseInf = new BaseInf("结算手续费(元)", "getStlFee",Tools.formatAmt(stlSumFee));

baseInfList.add(baseInf);

baseInf = new BaseInf("状态", "getSTATEStr");

baseInfList.add(baseInf);

return baseInfList;

}

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.math.BigDecimal;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.List;

import java.util.Map;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.util.HSSFColor;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.Font;

import org.apache.poi.ss.usermodel.IndexedColors;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {

    // 私有构造方法禁止new实例

    private ExcelUtil() {

    }

    // 日志工具

    // private static final Logger logger =

    // LoggerFactory.getLogger(ExcelUtil.class);

    // 默认日期格式

    private static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日 hh点mm分ss秒";

    // 默认行高

    //Columns

    private static final Short DEFAULT_COLUMNS_HEIGHT = 400;

    private static final Short DEFAULT_COLUMNS_WEIGHT = 1700;

 

    /**

     * 将工作表输出到浏览器中

     * @param response 响应流

     * @param workbook 创建完成的工作表

     * @param fileName 文件名

     * @param sufferNm 文件后缀名

     * @throws Exception 异常

     */

    public static void workbook2InputStream(HttpServletResponse response, Workbook workbook, String fileName,

                                            String sufferNm) throws Exception {

        //除去fileName的空格

        fileName = fileName.replace(" ", "");

        try (ServletOutputStream out = response.getOutputStream()) {

            response.setCharacterEncoding("utf-8");

            response.setHeader("Content-type", "application/vnd.ms-excel");

            response.setHeader("Content-Disposition",

                    "attachment; filename=" + new String((fileName).getBytes("gb2312"), "ISO8859-1") + sufferNm);

            // 设置下载头信息

            response.setContentType("application nd.ms-excel; charset=utf-8");

            workbook.write(out);

            out.flush();

        }

    }

 

    /**

     * 实体类单层嵌套 有统计栏

     */

    public static Workbook createWorkbookHasCount(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list)

            throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,

            InvocationTargetException {

        return createWorkbook(version, sheetNm, baseInfList, list, null, true);

    }

    /**

     * 实体类单层嵌套 自定义是否有统计栏

     */

    public static Workbook createWorkbook(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list, Boolean openCount)

            throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,

            InvocationTargetException {

        return createWorkbook(version, sheetNm, baseInfList, list, null, openCount);

    }

 

    /**

     * 实体类单层嵌套 无统计栏

     */

    public static Workbook createWorkbook(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list)

            throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,

            InvocationTargetException {

        return createWorkbook(version, sheetNm, baseInfList, list, null, false);

    }

    /**

     * 创建一个数据表 实体类嵌套实体类

     * @param version     excel版本 2007 或者其他

     * @param sheetNm     sheet 名称

     * @param baseInfList 数据基础信息

     * @param list        数据

     * @param innerMethod 实体类多层嵌套

     * @return 构建完成的数据表对象

     * @throws SecurityException         安全异常

     * @throws NoSuchMethodException     方法没有异常

     * @throws InvocationTargetException 调用异常

     * @throws IllegalArgumentException  非法参数异常

     * @throws IllegalAccessException    非法访问异常

     * @see BaseInf

     */

    public static Workbook createWorkbook(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list,

                                          String innerMethod, Boolean openCount) throws NoSuchMethodException, SecurityException, IllegalAccessException,

            IllegalArgumentException, InvocationTargetException {

        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);

        Workbook workbook;

        if (version == 2007) {

            workbook = new XSSFWorkbook();

        } else {

            workbook = new HSSFWorkbook();

        }

        Sheet sheet = workbook.createSheet(isEmpty(sheetNm) ? "sheet1" : sheetNm);

        // 写入标题

        CellStyle titleStyle = titleStyle(workbook);

        // 创建标题行(第一行)

        Row titleRow = sheet.createRow(0);

        // 设置第一行的行高

        titleRow.setHeight(DEFAULT_COLUMNS_HEIGHT);

 

        // 设置序号

        sheet.setColumnWidth(0, DEFAULT_COLUMNS_WEIGHT);

        Cell cell = titleRow.createCell(0);

        setTitle(baseInfList, sheet, titleStyle, titleRow, cell);

 

        /*

         * 写入数据

         *

         * 写入数据按照先行 后列的的方式进行

         *

         */

        CellStyle dataStyle = dataStyle(workbook);

        Row dataRow;

        for (int i = 0; i < list.size(); i++) {

            // 创建行

            dataRow = sheet.createRow(i + 1);

            // 创建列 此处为序号列

            cell = dataRow.createCell(0);

            cell.setCellType(Cell.CELL_TYPE_STRING);

            cell.setCellValue(i + 1);

            cell.setCellStyle(titleStyle);

            // 序号列创建完毕 开始创建数据列

            for (int j = 0; j < baseInfList.size(); j++) {

                // 创建数据列

                cell = dataRow.createCell(j + 1);

                BaseInf baseInf = baseInfList.get(j);

                // 设值

                Method method;

                Object value;

                if (innerMethod != null) {

                    method = list.get(i).getClass().getMethod(innerMethod);

                    Object obj = method.invoke(list.get(i));

                    method = obj.getClass().getMethod(baseInf.getColumMethod());

                    value = method.invoke(obj);

                } else {

                    method = list.get(i).getClass().getMethod(baseInf.getColumMethod());

                    value = method.invoke(list.get(i));

                }

                String returnType = method.getReturnType().getName().toLowerCase();

                //数据处理类 处理数据库原始生成数据

                Class<?> valueClazz = baseInf.getClazz();

                Method valueMethod = baseInf.getMethod();

                if (valueClazz != null && valueMethod != null) {

                    value = valueMethod.invoke(valueClazz, value);

                }

                cell.setCellStyle(dataStyle);

                // 转义列表

                Map<String, String> transMap = baseInf.getMap();

                // 判断是否需要转义

                if (transMap == null) {

                    if (returnType.contains("string")) {

                        cell.setCellType(Cell.CELL_TYPE_STRING);

                        cell.setCellValue(value == null ? "" : value.toString());

                    } else if (returnType.contains("integer") || returnType.contains("int")

                            || returnType.contains("bigdecimal") || returnType.contains("double")

                            || returnType.contains("long") || returnType.contains("float")) {

                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);

                        if (value != null) {

                            cell.setCellValue(new Double(value.toString()));

                        } else {

                            cell.setCellValue(0.0d);

                        }

                    } else if (returnType.contains("date")) {

                        cell.setCellType(Cell.CELL_TYPE_STRING);

                        cell.setCellValue(value == null ? null : sdf.format((Date) value));

                    } else {

                        cell.setCellType(Cell.CELL_TYPE_STRING);

                        cell.setCellValue(value == null ? "" : value.toString());

                    }

                } else {

                    cell.setCellType(Cell.CELL_TYPE_STRING);

                    String cellValue = value == null ? "" : transMap.get(tse(value.toString()));

                    cell.setCellValue(cellValue == null ? tse(value.toString()) : cellValue);

                }

            }

        }

        // 创建统计行

        if (openCount) {

            openCount(baseInfList, sheet, titleStyle, dataStyle, list.size());

        }

        return workbook;

    }

    public static Workbook createWorkbookForMap(int version, String sheetNm, List<BaseInf> baseInfList, List<Map<String,Object>> list,Boolean openCount) throws SecurityException, IllegalAccessException,

            IllegalArgumentException, InvocationTargetException {

        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);

        Workbook workbook;

        if (version == 2007) {

            workbook = new XSSFWorkbook();

        } else {

            workbook = new HSSFWorkbook();

        }

        Sheet sheet = workbook.createSheet(isEmpty(sheetNm) ? "sheet1" : sheetNm);

        // 写入标题

        CellStyle titleStyle = titleStyle(workbook);

        // 创建标题行(第一行)

        Row titleRow = sheet.createRow(0);

        // 设置第一行的行高

        titleRow.setHeight(DEFAULT_COLUMNS_HEIGHT);

        // 设置序号

        sheet.setColumnWidth(0, DEFAULT_COLUMNS_WEIGHT);

        Cell cell = titleRow.createCell(0);

        setTitle(baseInfList, sheet, titleStyle, titleRow, cell);

        /*

         * 写入数据

         * 写入数据按照先行 后列的的方式进行

         */

        CellStyle dataStyle = dataStyle(workbook);

        Row dataRow;

        for (int i = 0; i < list.size(); i++) {

            // 创建行

            dataRow = sheet.createRow(i + 1);

            // 创建列 此处为序号列

            cell = dataRow.createCell(0);

            cell.setCellType(Cell.CELL_TYPE_STRING);

            cell.setCellValue(i + 1);

            cell.setCellStyle(titleStyle);

            // 序号列创建完毕 开始创建数据列

            for (int j = 0; j < baseInfList.size(); j++) {

                // 创建数据列

                cell = dataRow.createCell(j + 1);

                BaseInf baseInf = baseInfList.get(j);

                // 设值

                Object value = list.get(i).get(baseInf.getColumMethod());

                //数据处理类 处理数据库原始生成数据

                Class<?> valueClazz = baseInf.getClazz();

                Method valueMethod = baseInf.getMethod();

                if (valueClazz != null && valueMethod != null) {

                    value = valueMethod.invoke(valueClazz, value);

                }

                cell.setCellStyle(dataStyle);

                // 转义列表

                Map<String, String> transMap = baseInf.getMap();

                // 判断是否需要转义

                if (transMap == null) {

                    if(value instanceof String){

                        cell.setCellType(Cell.CELL_TYPE_STRING);

                        cell.setCellValue(value.toString());

                    }

                    if(value instanceof Integer || value instanceof BigDecimal || value instanceof Long){

                        cell.setCellType(Cell.CELL_TYPE_NUMERIC);

                        cell.setCellValue(new Double(value.toString()));

                    }

                    if(value instanceof Date){

                        cell.setCellType(Cell.CELL_TYPE_STRING);

                        cell.setCellValue(sdf.format((Date) value));

                    }else {

                        cell.setCellType(Cell.CELL_TYPE_STRING);

                        cell.setCellValue(value == null ? "" : value.toString());

                    }

                } else {

                    cell.setCellType(Cell.CELL_TYPE_STRING);

                    String cellValue = value == null ? "" : transMap.get(tse(value.toString()));

                    cell.setCellValue(cellValue == null ? tse(value.toString()) : cellValue);

                }

            }

        }

        // 创建统计行

        if (openCount) {

            openCount(baseInfList, sheet, titleStyle, dataStyle, list.size());

        }

        return workbook;

    }

    /**

     * 设置标题

     */

    private static void setTitle(List<BaseInf> baseInfList, Sheet sheet, CellStyle titleStyle, Row titleRow, Cell cell) {

        cell.setCellType(Cell.CELL_TYPE_STRING);

        cell.setCellValue("序号");

        cell.setCellStyle(titleStyle);

        // 其他标题

        for (int i = 0; i < baseInfList.size(); i++) {

            String titleName = baseInfList.get(i).getTitleName();

            // 设置单元格的宽

            sheet.setColumnWidth(i + 1, titleName.length() * DEFAULT_COLUMNS_WEIGHT);

            cell = titleRow.createCell(i + 1);

            cell.setCellType(Cell.CELL_TYPE_STRING);

            cell.setCellValue(titleName);

            cell.setCellStyle(titleStyle);

        }

    }

    private static void openCount(List<BaseInf> baseInfList, Sheet sheet, CellStyle titleStyle, CellStyle dataStyle, int size) {

        Row dataRow;

        Cell cell;

        dataRow = sheet.createRow(size + 1);

        // 创建列 此处为序号列

        cell = dataRow.createCell(0);

        cell.setCellType(Cell.CELL_TYPE_STRING);

        cell.setCellValue("统计");

        cell.setCellStyle(titleStyle);

        for (int i = 0; i < baseInfList.size(); i++) {

            BaseInf baseInf = baseInfList.get(i);

            cell = dataRow.createCell(i + 1);

            cell.setCellType(Cell.CELL_TYPE_STRING);

            cell.setCellStyle(dataStyle);

            if (baseInf.getCount() != null) {

                cell.setCellValue(baseInf.getCount());

            } else {

                cell.setCellValue("");

            }

        }

    }

    /**

     * 删除字符串内的回车 空格和两端空白

     */

    private static String tse(String str) {

        return str == null ? "" : str.replace(" ", "").replace("/r", "").replace("/n", "").trim();

    }

    // 判断非空

    private static boolean isEmpty(String str) {

        return str == null || "".equals(str.trim());

    }

    /**

     * 设置标题样式

     * @param workbook 工作表

     * @return 标题样式

     */

    private static CellStyle titleStyle(Workbook workbook) {

        CellStyle titleStyle = workbook.createCellStyle();

        titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());

        titleStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

        // 居中

        titleStyle.setAlignment(CellStyle.ALIGN_CENTER_SELECTION);

        titleStyle.setBorderLeft((short) 1);

        titleStyle.setBorderRight((short) 1);

        titleStyle.setBorderBottom((short) 1);

        titleStyle.setBorderTop((short) 1);

        Font font = workbook.createFont();

        font.setFontHeightInPoints((short) 12);// 设置字体大小

        titleStyle.setFont(font);// 选择需要用到的字体格式

        return titleStyle;

    }

    /**

     * 数据样式

     *

     * @param workbook 工作表

     * @return 数据样式

     */

    private static CellStyle dataStyle(Workbook workbook) {

        CellStyle dataStyle = workbook.createCellStyle();

        dataStyle.setBorderBottom((short) 1);

        dataStyle.setBorderLeft((short) 1);

        dataStyle.setBorderRight((short) 1);

        dataStyle.setBorderTop((short) 1);

        dataStyle.setBottomBorderColor(HSSFColor.BLACK.index);

        return dataStyle;

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值