• Spring MVC 通过反射将数据导出到excel


    直接上代码

    // 导出excel方法
        @RequestMapping("exportExcel")
        public void exportExcel(HttpServletRequest request, HttpServletResponse response)
        {
            List<TDataContacts> contactsList=dataContactsService.getContacts();
    
            HttpSession session = request.getSession();
            session.setAttribute("state", null);
            // 生成提示信息,
            response.setContentType("application/vnd.ms-excel");
            String codedFileName = null;
            OutputStream fOut = null;
            try
            {
                // 进行转码,使其支持中文文件名
                codedFileName = java.net.URLEncoder.encode("中文", "UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
                // response.addHeader("Content-Disposition", "attachment;   filename=" + codedFileName + ".xls");
                // 产生工作簿对象
                HSSFWorkbook workbook = new HSSFWorkbook();
                //产生工作表对象
                HSSFSheet sheet = workbook.createSheet();
                int rowIndex = 1,cellIndex = 0;
                Field[] field = contactsList.get(0).getClass().getDeclaredFields();        //获取实体类的所有属性,返回Field数组
                HSSFRow headerRow = sheet.createRow(0);//创建一行
                while (cellIndex<field.length){
                    HSSFCell cell = headerRow.createCell(cellIndex);//创建一列
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    cell.setCellValue(field[cellIndex].getName());
                    cellIndex++;
                }
    
                for(int i=0;i<contactsList.size();i++){
                    cellIndex=0;
                    HSSFRow currentRow = sheet.createRow(rowIndex);//创建一行
                    while (cellIndex<field.length){
                        HSSFCell cell = currentRow.createCell(cellIndex);//创建一列
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        Object value=InvokeUtility.getFieldValueByName(field[cellIndex].getName(),contactsList.get(i));//通过反射获取属性的value
                        String returnValue;
                        if(value!=null){
                            if(value.getClass()== Date.class){
                                DateFormat to_type   = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                returnValue=to_type.format(value);
                            }
                            else{
                                returnValue=String.valueOf(value);
                            }
                        }else{
                            returnValue="";
                        }
                        cell.setCellValue(returnValue);
                        cellIndex++;
                    }
                    rowIndex++;
                }
                fOut = response.getOutputStream();
                workbook.write(fOut);
            }
            catch (UnsupportedEncodingException e1)
            {}
            catch (Exception e)
            {}
            finally
            {
                try
                {
                    fOut.flush();
                    fOut.close();
                }
                catch (IOException e)
                {}
                session.setAttribute("state", "open");
            }
            System.out.println("文件生成...");
        }

    然后是反射工具类

    package com.huanshare.utility;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.*;
    
    /**
     * Created by huanshare
     */
    public class InvokeUtility {
        /**
         * 根据属性名获取属性值
         * */
        public static Object getFieldValueByName(String fieldName, Object o) {
            try {
                String firstLetter = fieldName.substring(0, 1).toUpperCase();
                String getter = "get" + firstLetter + fieldName.substring(1);
                Method method = o.getClass().getMethod(getter, new Class[] {});
                Object value = method.invoke(o, new Object[] {});
                return value;
            } catch (Exception e) {
                return null;
            }
        }
    
        /**
         * 获取属性名数组
         * */
        public static String[] getFiledName(Object o){
            Field[] fields=o.getClass().getDeclaredFields();
            String[] fieldNames=new String[fields.length];
            for(int i=0;i<fields.length;i++){
                System.out.println(fields[i].getType());
                fieldNames[i]=fields[i].getName();
            }
            return fieldNames;
        }
    
        /**
         * 获取属性类型(type),属性名(name),属性值(value)的map组成的list
         * */
        public static  List getFiledsInfo(Object o){
            Field[] fields=o.getClass().getDeclaredFields();
            String[] fieldNames=new String[fields.length];
            List list = new ArrayList();
            Map infoMap=null;
            for(int i=0;i<fields.length;i++){
                infoMap = new HashMap();
                infoMap.put("type", fields[i].getType().toString());
                infoMap.put("name", fields[i].getName());
                infoMap.put("value", getFieldValueByName(fields[i].getName(), o));
                list.add(infoMap);
            }
            return list;
        }
    
        /**
         * 获取对象的所有属性值,返回一个对象数组
         * */
        public Object[] getFiledValues(Object o){
            String[] fieldNames=this.getFiledName(o);
            Object[] value=new Object[fieldNames.length];
            for(int i=0;i<fieldNames.length;i++){
                value[i]=this.getFieldValueByName(fieldNames[i], o);
            }
            return value;
        }
    }
  • 相关阅读:
    STL常用容器☞String容器
    初识STL
    函数模板
    多态
    运算符重载
    友元
    对象的初始化和清理
    C++内存分区模型
    传值和传地址
    const的使用
  • 原文地址:https://www.cnblogs.com/myhappylife/p/5067303.html
Copyright © 2020-2023  润新知