java poi 生成execl

TradeExecl.xmljava

<?xml version="1.0" encoding="UTF-8"?>
<columns>
    <column key="tradeSn">交易流水号</column>
    <column key="paymentUserName">支付方式姓名</column>
    <column key="tradeType">交易类型</column>
    <column key="price">支付金额</column>
    <column key="paymentType">支付类型</column>
    <column key="tradeState">交易结果</column>
    <column key="createTime">支付时间</column>
    <column key="presentMoney">备注</column>
</columns>web

 

=====================struts2=====================spring

/***
     * 生成用户充值execl 并下载
     */
    public  String  downloadExecl(){
        try {
            SAXBuilder builder=new SAXBuilder(false);    
            //Document document = builder.build("D:/hjqProject2015/demo/src/com/kaiyuan/hjq/mq/hh.xml");
            Document document =builder.build(TradeRecodAction.class.getResourceAsStream("tradeExecl.xml"));
            Element keys=document.getRootElement();
            List<Element> keysList=keys.getChildren("column"); 
             // 第一步,建立一个webbook,对应一个Excel文件  
            HSSFWorkbook wb = new HSSFWorkbook();  
            // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
            HSSFSheet sheet = wb.createSheet("用户充值记录表一"); 
            // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
            HSSFRow row = sheet.createRow((int) 0);  
            // 第四步,建立单元格,并设置值表头 设置表头居中  
            HSSFCellStyle style = wb.createCellStyle();  
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一个居中格式  
            
            logger.info("开始时间:{}",System.currentTimeMillis());
            // 第五步,写入实体数据 实际应用中这些数据从数据库获得,  
            Grid grid =  traderecordServiceRemoteI.findTradeRecordxBybond(data,page, 100000);
            List<TradeRecordVo>  result = grid.getRows();
            if(keysList!=null && keysList.size()>0){
                 for (int i=0;i<keysList.size();i++) {
                      HSSFCell cell = row.createCell((short) i);  
                      cell.setCellValue(keysList.get(i).getValue());  
                      cell.setCellStyle(style);  
                      //System.out.println(keysList.get(i).getAttribute("key").getValue());
                 }
             }
            if(result!=null && result.size() >0){
                 for (int j = 0; j < result.size(); j++) {
                     TradeRecordVo trv = result.get(j);
                     row = sheet.createRow((int) j + 1); 
                     // 第四步,建立单元格,并设置值  
                     for (int i=0;i<keysList.size();i++) {
                         String value = ReflectUtil.getBeanProperty(trv, keysList.get(i).getAttribute("key").getValue());
                         if(value!=null){
                             row.createCell((short) i).setCellValue(value);
                         }
                     }
                 }
           }
            //第七步,将文件存到流中
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            byte[] fileContent = os.toByteArray();
            ByteArrayInputStream is = new ByteArrayInputStream(fileContent);
            
            inputStream = is;             //文件流
            //filename = "payBond2.xls"; //设置下载的文件名
            logger.info("结束时间:{}",System.currentTimeMillis());
        } catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        return "success";
    }sql

=======================配置文件=======================
     <!-- 下载用户充值记录 -->
        <action name="downloadExecl" class="com.zbzwl.action.traderecod.TradeRecodAction">  
            <result name="success" type="stream">  
                <param name="contentType">application/vnd.ms-excel;charset=utf-8</param>  
                <param name="inputName">inputStream</param>  
                <param name="contentDisposition">attachment;filename="payBond.xls"</param>  
                <param name="bufferSize">8192</param>  
            </result>  
        </action> 数据库

======================ReflectUtil.java======================================apache

备注 这个地方用反射了  经过xmlkey 去找到bean的value json

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;数组

import org.apache.commons.beanutils.BeanUtils;mvc

public class ReflectUtil {app

    public static  String  getValueByproperty(Object model,String key){
        try{
            Field[] field = model.getClass().getDeclaredFields(); // 获取实体类的全部属性,返回Field数组
            for (Field field2 : field) {
                if(key.equals(field2.getName())){
                    System.out.println("进入反射方法  key="+key);
                    String type = field2.getGenericType().toString(); // 获取属性的类型
                    
                    String name = field2.getName().substring(0, 1).toUpperCase() + field2.getName().substring(1); // 将属性的首字符大写,方便构造get,set
                    if (type.equals("class java.lang.String")) { 
                        Method Gm =model.getClass().getMethod("get" + name);
                        return  (String) Gm.invoke(model);
                    }
                    if (type.equals("class java.sql.Timestamp")) { 
                        Method Gm =model.getClass().getMethod("get" + name);
                        return  ((Timestamp) Gm.invoke(model)).toString();
                    }
                    if (type.equals("class java.lang.Double")) { 
                        Method Gm =model.getClass().getMethod("get" + name);
                        return  ((Double) Gm.invoke(model)==null?0.0:Gm.invoke(model)).toString();
                    }
                     
                }else{
                    System.out.println("elsekey=="+key);
                }
            }
        }catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
    
    
    public static  String  getBeanProperty(Object model,String key){
        try {
            String beanValue = BeanUtils.getProperty(model, key);
            //System.out.println("key=="+key+"=="+beanValue);
            return beanValue;
        } catch (IllegalAccessException | InvocationTargetException
                | NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

 

=============================springmvc====================================

@Autowired
    private RewardPostalServiceI   rewardPostalServiceI;
    private String[] rowName = {"申请日期","姓名","帐户余额","提现总额","身份证照片","审核时间","审核结果"} ;
     /*
     * 导出数据
     * */
    @RequestMapping(value = "/exceldownload")
    public void export2(HttpServletResponse  response,String idsarray) throws Exception{
        List<Object[]>  dataList = new ArrayList<Object[]>();
        Json<List<RewardPostalOwnVo>> json = new Json<List<RewardPostalOwnVo>>();
            RewardPostalOwnVo rewardpostalvo = new RewardPostalOwnVo();
            String [] str = idsarray.split(",");
            List<Long> ids = new ArrayList<Long>();
            for (String string : str) {
                ids.add(Long.parseLong(string));
            }
            rewardpostalvo.setIds(ids);
            json =  rewardPostalServiceI.findRewardPostalByIds(rewardpostalvo.getIds());
            List<RewardPostalOwnVo> result = json.getObj();
            SimpleDateFormat  sdf = new SimpleDateFormat("yyyy.MM.dd  HH:mm");
            for (RewardPostalOwnVo rewardPostalOwnVo : result) {
                Object[] objs = new Object[7];
                objs[0] = sdf.format(rewardPostalOwnVo.getCreatetime());
                objs[1] = rewardPostalOwnVo.getUsername();
                objs[2] = rewardPostalOwnVo.getTotalreward();
                objs[3] = rewardPostalOwnVo.getPostalmoney();
                objs[4] = rewardPostalOwnVo.getIdcardimg();
                objs[5] = sdf.format(rewardPostalOwnVo.getReviewedtime());
                objs[6] = rewardPostalOwnVo.getStatetype();
                dataList.add(objs);
            }
        try{
            HSSFWorkbook workbook = new HSSFWorkbook();                     // 建立工做簿对象
            HSSFSheet sheet = workbook.createSheet("待支付明细");                 // 建立工做表
            
            // 产生表格标题行
            HSSFRow rowm = sheet.createRow(0);
            HSSFCellStyle cellstyle = workbook.createCellStyle(); 
            cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 定义所需列数
            int columnNum = rowName.length;
           // HSSFRow rowRowName = sheet.createRow(2);                // 在索引2的位置建立行(最顶端的行开始的第二行)
            
            // 将列头设置到sheet的单元格中
            for(int n=0;n<columnNum;n++){
                HSSFCell  cellRowName = rowm.createCell(n);               //建立列头对应个数的单元格
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);             //设置列头单元格的数据类型
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                cellRowName.setCellValue(text);                                 //设置列头单元格的值
                cellRowName.setCellStyle(cellstyle);                       //设置列头单元格样式
            }
            
            //将查询出的数据设置到sheet对应的单元格中
            for(int i=0;i<dataList.size();i++){
                
                Object[] obj = dataList.get(i);//遍历每一个对象
                HSSFRow row = sheet.createRow(i+1);//建立所需的行数
                HSSFCell  cell =  row.createCell(0, HSSFCell.CELL_TYPE_STRING);
                cell.setCellValue(obj[0]==null?"":obj[0].toString()); 
                cell.setCellStyle(cellstyle);
                HSSFCell  cell1 =   row.createCell(1, HSSFCell.CELL_TYPE_STRING);
                cell1.setCellValue(obj[1]==null?"":obj[1].toString()); 
                cell1.setCellStyle(cellstyle);
                HSSFCell  cell2 =  row.createCell(2, HSSFCell.CELL_TYPE_STRING);
                cell2.setCellValue(obj[2]==null?"":obj[2].toString()); 
                cell2.setCellStyle(cellstyle);
                HSSFCell  cell3 =  row.createCell(3, HSSFCell.CELL_TYPE_STRING);
                cell3.setCellValue(obj[3]==null?"":obj[3].toString()); 
                cell3.setCellStyle(cellstyle);
                HSSFCell  cell4 =  row.createCell(4, HSSFCell.CELL_TYPE_STRING);
                cell4.setCellValue(obj[4]==null?"":obj[4].toString()); 
                cell4.setCellStyle(cellstyle);
                HSSFCell  cell5 =  row.createCell(5, HSSFCell.CELL_TYPE_STRING);
                cell5.setCellValue(obj[5]==null?"":obj[5].toString()); 
                cell5.setCellStyle(cellstyle);
                HSSFCell  cell6 =  row.createCell(6, HSSFCell.CELL_TYPE_STRING);
                cell6.setCellValue(obj[6]==null?"":obj[6].toString()); 
                cell6.setCellStyle(cellstyle);
            }
            //让列宽随着导出的列长自动适应
            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-2) * 256);
                }else{
                    sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
                }
            }
            
            if(workbook !=null){
                try
                {
                    String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
                    String headStr = "attachment; filename=\"" + fileName + "\"";
                  //  response = getResponse();
                    response.setContentType("APPLICATION/OCTET-STREAM");
                    response.setHeader("Content-Disposition", headStr);
                    OutputStream out = response.getOutputStream();
                    workbook.write(out);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

        }catch(Exception e){             e.printStackTrace();         }              }

相关文章
相关标签/搜索