excel模板导入,对象中有对象递归来实现的,导出浏览器是href来链接,可以设计模板的行和类

package com.jq.cqjypt.dyrz.service.impl;




import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletResponse;


import org.apache.poi.ss.usermodel.Cell;
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.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;


import com.jq.cqjypt.dyrz.service.ExportExcelService;


/**
 * 导出exportExcel
* @Title: ExportExcelImpl.java 
* @date 2018年1月8日 上午10:33:17 
* @author lxw
*
 */
@Service
public class ExportExcelServiceImpl implements ExportExcelService{  

    /**  
     *   
     */  
    private static final long serialVersionUID = 1L;  


    // 声明Wrokbook
private Workbook workbook;
//声明sheet表格
private Sheet sheet;


   
    
@Value(value="${dy.templatePath}")
private String templatePath;

@Value(value="${dy.outPutPath}")
private String outPutPath;
/**  
     * 生成excel并下载  
     * @Param list    要插入的数据
     * @Param numRow  模板标题占用的行数
     * @Param numCell 模板占用的列数
     * @Param excelTemName 模板名称
     * @Param excelOutName 导出名称
     */


public String exportExcel(List<Object> list, int numRow, int numCell, String excelTemName, String excelOutName,HttpServletResponse response) {
    String outPath=outPutPath+new Date().getTime()+excelOutName;
List<Map<String, String>> datas=this.getKeyAndValue(list);
replaceConstant(datas, numRow, numCell, excelTemName);
//保存硬盘
writeFilePath(outPath);
//返回页面
InputStream instream;
try {
instream = new FileInputStream(new File(outPath));
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(excelOutName, "UTF-8"));
FileCopyUtils.copy(instream, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}  
    




public void replaceConstant(List<Map<String, String>> datas,int numRow,int numCell,String excelTemName) {
  try {
workbook = WorkbookFactory.create(new File(templatePath+excelTemName));
//得到模版中第一个sheet表格
   sheet=workbook.getSheetAt(0);
}  catch (Exception e) {
e.printStackTrace();
}
  
  Row row = sheet.getRow(numRow);
String[] str = new String[row.getPhysicalNumberOfCells()];
for (int i=0;i<row.getPhysicalNumberOfCells();i++) {
Cell cell = row.getCell(i);
String cellValue = cell.getStringCellValue().trim();
// 如果当前模版中式#开头就是我们所需要替换的常量
if (cellValue.startsWith("#")) {
// 如果这一列#说明还有下一列
// 如果datas数据中包含有我们的值就进行常量设置
str[i] = cellValue.substring(1);
}
}
for(int x=0;x<datas.size();x++){
Row newRows = sheet.createRow(x+numRow);
for(int m=0;m<str.length;m++){
Cell cell = newRows.createCell(m+numCell);
cell.setCellValue(datas.get(x).get(str[m]));
}
}
}


//将数据到处到Excel中,保存到硬盘上
public void writeFilePath(String filePath){
  FileOutputStream fos=null;
  try {
   fos= new FileOutputStream(new File(filePath));
   workbook.write(fos);
  }  catch (Exception e) {
   e.printStackTrace();
   throw new RuntimeException("写入流失败!");
  }finally{
   try {
    fos.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
}
 
/**
     * 单个对象的所有键值
     * 
     * @param object
     *            单个对象
     */
    public  List<Map<String, String>> getKeyAndValue(List<Object> objs ) {
    List<Map<String, String>> list=new ArrayList<Map<String, String>>();
    for(Object obj:objs){
    Map<String, String> map = new HashMap<String, String>();
        list.add(getFieldsValueMap(obj, map));
    }
        return list;
    }
    /** 
   * 基本类型、包装类型、String类型 
   */ 
    public boolean isExist( String str) {
  String[] strs = {"java.lang.Integer",  
        "java.lang.Double",  
        "java.lang.Float",  
        "java.lang.Long",  
        "java.lang.Short",  
        "java.lang.Byte",  
        "java.lang.Boolean",  
        "java.lang.Character",  
        "java.lang.String", "java.util.Date","java.util.List","java.util.Map",
        "int","double","long","short","byte","boolean","char","float","date"};  
for (String tmp : strs) {
if (tmp.equals(str)) {
return true;
}
}
return false;
}
/*
  * 递归调用对象
  */
  public Map<String, String> getFieldsValueMap(Object obj,Map<String, String> map) {  
  Field[] fields = obj.getClass().getDeclaredFields();  
  for(Field f : fields){
   f.setAccessible(true);  
  String fieldType = f.getType().getName();
  Object val = new Object();
  try {
  if (isExist(fieldType)) {
val=f.get(obj);
  if(val!=null){
  map.put(f.getName(), val.toString());
  }
  }  else {
  getFieldsValueMap(f.get(obj),map);

  }catch (Exception e) {
e.printStackTrace();
}
  }
  return map;
    }
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值