xls大数据导入

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a target=_blank href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a target=_blank href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- 公共jsp -->
<jsp:include page="../../../common/taglibs.jsp" />
<jsp:include page="../../../common/flatHead.jsp" />
<!-- 公共css -->
<link href="${ctx }flat/css/reset.css" rel="stylesheet" type="text/css" />
<link href="${ctx }flat/css/systemManagement.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="${ctx}plugins/upload/uploadify.css" />
<script type="text/javascript" src="${ctx}plugins/upload/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="${ctx}js/common/ajaxfileupload.js?version=${version}"></script>
<%-- <script type="text/javascript" src="${ctx}js/logined/societygrid/common/importBasicData.js"></script> --%>
<script type="text/javascript" src="${ctx}js/logined/societygrid/common/importBasicData.js"></script>

</head>
<body class="bg_white">
<div class="importBox">
    <h4>选择导入文件&nbsp;&nbsp;<input type="file" name="fileToUpload" id="fileToUpload"/></h4>
    <p><span>暂时只支持导入Excel格式文件,后缀名为.xls</span><a href="${ctx}templates/${param.fileName}.xls" class="ml10">获取模板?</a></p>
    <p id="msg" style="color: red;height:20px"></p>
</div>
</body>
</html>


/**
 * 导入
 */
function uploadStore() {
	//var html = createImportUserHtml();
	var url = basePath+"logined/societygrid/common/importBasicData.jsp?fileName=门店信息导入模板";
	art.dialog.open(url,{
				id : 'importStore',
				title : '门店信息导入',
				width:'500px',
				height:"170px",
				lock : true,
				button : [/*{
							name : '验 证',
							callback : function() {
								checkFileFormat();
								return false;
							}
						},*/ {
							name : '导 入',
							callback : function() {
								var iframe = this.iframe.contentWindow;
								var url = basePath + 'store/importStore.action';
								iframe.startAjaxFileUpload(url);
								return false;
							}
						}, {
							name : '取 消',
							callback : function() {
								return true;
							}
						}]
			,close:function(){
				window.location.reload();
			}});

}

package cn.com.qytx.societygrid.utils.excel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAnnotation {
    // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入
    public String exportName();
}


package cn.com.qytx.societygrid.utils.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFName;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
 * 通用Excel导入
 *
 * @param <T>
 */
public class ExcelImport<T> {
    Class<T> clazz;
    public ExcelImport(Class<T> clazz) {
        this.clazz = clazz;
    }
    /**
     * 导入Excel
     *
     * @param titleIndex 表头索引
     * @param file       excel文件 路径
     * @param pattern
     * @return
     */
    public Collection<T> importExcel(int titleIndex, File file, String... pattern) {
        Collection<T> dist = new ArrayList();
        try {
            /**
             * 类反射得到调用方法
             */
            // 得到目标目标类的所有的字段列表
            Field filed[] = clazz.getDeclaredFields();
            // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
            Map fieldmap = new HashMap();
            // 循环读取所有字段
            for (int i = 0; i < filed.length; i++) {
                Field f = filed[i];
                // 得到单个字段上的Annotation
                ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
                // 如果标识了Annotationd的话
                if (exa != null) {
                    // 构造设置了Annotation的字段的Setter方法
                    String fieldname = f.getName();
                    String setMethodName = "set"
                            + fieldname.substring(0, 1).toUpperCase()
                            + fieldname.substring(1);
                    // 构造调用的method,
                    Method setMethod = clazz.getMethod(setMethodName,
                            new Class[]{f.getType()});
                    // 将这个method以Annotaion的名字为key来存入。
                    fieldmap.put(exa.exportName(), setMethod);
                }
            }
            /**
             * excel的解析开始
             */
            // 将传入的File构造为FileInputStream;
            FileInputStream in = new FileInputStream(file);
            // // 得到工作表
            HSSFWorkbook book = new HSSFWorkbook(in);
            // // 得到第一页
            HSSFSheet sheet = book.getSheetAt(0);
            // // 得到第一面的所有行
            Iterator<Row> row = sheet.rowIterator();
            /**
             * 标题解析
             */
            // 得到第一行,也就是标题行
            Row title = row.next();
            for (int i = 1; i < titleIndex; i++) {
                //获取表头
                title = row.next();
            }
            // 得到第一行的所有列
            Iterator<Cell> cellTitle = title.cellIterator();
            // 将标题的文字内容放入到一个map中。
            Map titlemap = new HashMap();
            // 从标题第一列开始
            // 循环标题所有的列的名称
            int i = 0;  // 从标题第一列开始
            // 循环标题所有的列
            while (cellTitle.hasNext()) {
                Cell cell = cellTitle.next();
                String value = cell.getStringCellValue();
                titlemap.put(i, value);
                i = i + 1;
            }
            /**
             * 解析内容行
             */
            //用来格式化日期的DateFormat
            SimpleDateFormat sf;
            if (pattern.length < 1) {
                sf = new SimpleDateFormat("yyyy-MM-dd");
            } else
                sf = new SimpleDateFormat(pattern[0]);
            while (row.hasNext()) {
                // 标题下的第一行
                Row rown = row.next();
                // 行的所有列
                Iterator<Cell> cellbody = rown.iterator();
                // 得到传入类的实例
                T tObject = clazz.newInstance();
                int k = 0;
                // 遍历一行的列
                int size=rown.getLastCellNum();//单元格数
                for(int j=0;j<size;j++){
                    Cell cell = rown.getCell(j, Row.CREATE_NULL_AS_BLANK);
                    // 这里得到此列的对应的标题
                    String titleString = (String) titlemap.get(k);
                    // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
                    if (fieldmap.containsKey(titleString)) {
                        Method setMethod = (Method) fieldmap.get(titleString);
                        //得到setter方法的参数
                        Type[] ts = setMethod.getGenericParameterTypes();
                        //只要一个参数
                        String xclass = ts[0].toString();
                        //判断参数类型
                        try {
                            if (xclass.equals("class java.lang.String")) {
                                if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
                                    //如果是数字,转换成字符串
                                    cell.setCellType(Cell.CELL_TYPE_STRING);
                                    setMethod.invoke(tObject, cell.getStringCellValue());
                                } else {
                                    setMethod.invoke(tObject, cell.getStringCellValue());
                                }
                            } else if (xclass.equals("class java.util.Date")) {
                                setMethod.invoke(tObject, sf.parse(cell.getStringCellValue()));
                            } else if (xclass.equals("class java.lang.Boolean")) {
                                Boolean boolname = true;
                                if (cell.getStringCellValue().equals("否")) {
                                    boolname = false;
                                }
                                setMethod.invoke(tObject, boolname);
                            } else if (xclass.equals("class java.lang.Integer")) {
                                setMethod.invoke(tObject, new Integer(cell.getStringCellValue()));
                            } else if (xclass.equals("class java.lang.Long")) {
                                setMethod.invoke(tObject, new Long(cell.getStringCellValue()));
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            continue;
                        }
                    }
                    // 下一列
                    k = k + 1;
                }
                dist.add(tObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return dist;
    }
    /**
     * 根据Cell名称导入Excel
     *
     * @param titleIndex 表头索引
     * @param file       excel文件 路径
     * @param pattern
     * @return
     */
    public Collection<T> importExcelByCellName(int titleIndex, Map titlemap, File file, String... pattern) {
        Collection<T> dist = new ArrayList();
        try {
            /**
             * 类反射得到调用方法
             */
            // 得到目标目标类的所有的字段列表
            Field filed[] = clazz.getDeclaredFields();
            // 将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中
            Map fieldmap = new HashMap();
            // 循环读取所有字段
            for (int i = 0; i < filed.length; i++) {
                Field f = filed[i];
                // 得到单个字段上的Annotation
                ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
                // 如果标识了Annotationd的话
                if (exa != null) {
                    // 构造设置了Annotation的字段的Setter方法
                    String fieldname = f.getName();
                    String setMethodName = "set"
                            + fieldname.substring(0, 1).toUpperCase()
                            + fieldname.substring(1);
                    // 构造调用的method,
                    Method setMethod = clazz.getMethod(setMethodName,
                            new Class[]{f.getType()});
                    // 将这个method以Annotaion的名字为key来存入。
                    fieldmap.put(exa.exportName(), setMethod);
                }
            }
            /**
             * excel的解析开始
             */
            // 将传入的File构造为FileInputStream;
            FileInputStream in = new FileInputStream(file);
            // // 得到工作表
            HSSFWorkbook book = new HSSFWorkbook(in);
            // // 得到第一页
            HSSFSheet sheet = book.getSheetAt(0);
            // // 得到第一面的所有行
            Iterator<Row> row = sheet.rowIterator();
            /**
             * 标题解析
             */
            // 得到第一行,也就是标题行
            Row title = row.next();
            for (int i = 1; i < titleIndex; i++) {
                //获取表头
                title = row.next();
            }
            // 得到第一行的所有列
            Iterator<Cell> cellTitle = title.cellIterator();
            /**
             * 解析内容行
             */
            //用来格式化日期的DateFormat
            SimpleDateFormat sf;
            if (pattern.length < 1) {
                sf = new SimpleDateFormat("yyyy-MM-dd");
            } else
                sf = new SimpleDateFormat(pattern[0]);
            while (row.hasNext()) {
                // 标题下的第一行
                Row rown = row.next();
                // 行的所有列
                Iterator<Cell> cellbody = rown.cellIterator();
                // 得到传入类的实例
                T tObject = clazz.newInstance();
                int k = 1;
                // 遍历一行的列
                int size=rown.getLastCellNum();//单元格数
                for(int j=0;j<size;j++){
                    Cell cell = rown.getCell(j, Row.CREATE_NULL_AS_BLANK);
                    // 这里得到此列的对应的标题
                    String titleString = (String) titlemap.get(k);
                    // 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
                    if (fieldmap.containsKey(titleString)) {
                        Method setMethod = (Method) fieldmap.get(titleString);
                        //得到setter方法的参数
                        Type[] ts = setMethod.getGenericParameterTypes();
                        //只要一个参数
                        String xclass = ts[0].toString();
                        //判断参数类型
                        try {
                            if (xclass.equals("class java.lang.String")) {
                                if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
                                    //如果是数字,转换成字符串
                                    cell.setCellType(Cell.CELL_TYPE_STRING);
                                    setMethod.invoke(tObject, cell.getStringCellValue());
                                } else {
                                    setMethod.invoke(tObject, cell.getStringCellValue());
                                }
                            } else if (xclass.equals("class java.util.Date")) {
                                setMethod.invoke(tObject, sf.parse(cell.getStringCellValue()));
                            } else if (xclass.equals("class java.lang.Boolean")) {
                                Boolean boolname = true;
                                if (cell.getStringCellValue().equals("否")) {
                                    boolname = false;
                                }
                                setMethod.invoke(tObject, boolname);
                            } else if (xclass.equals("class java.lang.Integer")) {
                                setMethod.invoke(tObject, new Integer(cell.getStringCellValue()));
                            } else if (xclass.equals("class java.lang.Long")) {
                                setMethod.invoke(tObject, new Long(cell.getStringCellValue()));
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            continue;
                        }
                    }
                    // 下一列
                    k = k + 1;
                }
                dist.add(tObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return dist;
    }
    public static void main(String[] args) {
        //生成模板
        String[] headers = new String[3];
        headers[0] = "姓名";
        headers[1] = "手机";
        headers[2] = "职务";
        try {
            FileOutputStream fileOut = null;
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            // fileOut = new FileOutputStream("E:/" + df.format(new Date()) + ".xls");
            // ExcelUtils.createTemplate(fileOut,headers);
            // fileOut.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

package cn.com.qytx.societygrid.action.store;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import cn.com.qytx.cbb.org.action.CheckUtil;
import cn.com.qytx.cbb.org.util.ExportExcel;
import cn.com.qytx.platform.base.action.BaseActionSupport;
import cn.com.qytx.platform.org.domain.UserInfo;
import cn.com.qytx.societygrid.domain.Area;
import cn.com.qytx.societygrid.domain.Store;
import cn.com.qytx.societygrid.service.IArea;
import cn.com.qytx.societygrid.service.IStore;
import cn.com.qytx.societygrid.utils.excel.ExcelImport;
import cn.com.qytx.societygrid.vo.StoreVo;
/**
 * 
 * <br/>功能: 门店导入
 * <br/>版本: 1.0
 * <br/>开发人员: 潘博
 * <br/>创建日期: 2014-8-15
 * <br/>修改日期: 2014-8-15
 * <br/>修改列表:
 */
public class StoreImportAction extends BaseActionSupport{
 private static final long serialVersionUID = 1L;
 @Resource
 private IArea areaService;
 @Resource
 private IStore storeService;
 
 private File fileToUpload;
    private String uploadFileName;//设置上传文件的文件名
    private String uploadContentType;//上传文件的类型
    private String file;//上传的文件
    private List<StoreVo> erroStoreVoList=new ArrayList<StoreVo>();
    private String errorFile;
 
  
    /**导入门店信息
     * @return
     * @throws Exception
     */
    public String importStore() throws Exception {
        try {
         UserInfo userInfo = this.getLoginUser();
         if(userInfo != null){
          
         
         String result = "";
            if (uploadFile()) {
             File tempFile = new File(file);
             if(!tempFile.exists()){
              result = "要导入的文件不存在,请重新导入!";
              return null;
             }
                ExcelImport<StoreVo> storeExcel = new ExcelImport(StoreVo.class);
             List<StoreVo> storeVoList = (ArrayList) storeExcel.importExcel(2,tempFile);
             int importSuccessNum = 0;
             if(storeVoList != null && storeVoList.size() > 0){
              //验证是否是正确的
              Map<String,String> areaCodeMap = areaService.getAreaToMap();
              String areaName = "";
              String areaCode = "";//地区编码
              String storeName = "";//门店名称
              String licenseCode = "";//营业执照编码
              String storeArea = "";//门店场所面积
              String storeAddr = "";//门店地址
              String businessScope = "";//经营范围
              String officerName = "";//负责人
              String legalPerson = "";//法人
              String phone = "";//联系电话
              String remark = "";//备注
              for(int i = 0;i < storeVoList.size();i++){
               boolean isErrorRecord = true;
               StoreVo storeVo = storeVoList.get(i);
               areaName = storeVo.getAreaName();
               storeName = storeVo.getStoreName();
               licenseCode = storeVo.getLicenseCode();
               storeArea = storeVo.getStoreArea();
               storeAddr = storeVo.getStoreAddr();
               businessScope = storeVo.getBusinessScope();
               officerName = storeVo.getOfficerName();
               legalPerson = storeVo.getLegalPerson();
               phone = storeVo.getPhone();
               remark = storeVo.getRemark();
               StringBuffer errorRecord = new StringBuffer();
               //验证所属辖区
               if(StringUtils.isNotBlank(areaName)){
                if(areaCodeMap.containsKey(areaName)){
                 areaCode = areaCodeMap.get(areaName);
                }else{
                 errorRecord.append("<所属辖区不存在>");
                 isErrorRecord = false;
                }
               }else{
                errorRecord.append("<所属辖区不能为空>");
                isErrorRecord = false;
               }
               //验证门店名称
               if(StringUtils.isNotBlank(storeName)){
                if(storeName.length() > 20){
                 errorRecord.append("<门店名称长度不能超过20位>");
                 isErrorRecord = false;
                }else{
                 Store st = new Store();
                 st.setStoreName(storeName);
                 Store store = storeService.findByStore(st);
                 if(store!=null){
                  errorRecord.append("<门店名称不能重复!>");
                     isErrorRecord = false;
                 }
                }
               }else{
                errorRecord.append("<门店名称不能为空!>");
             isErrorRecord = false;
               }
               //验证营业执照编码
               if(StringUtils.isNotBlank(licenseCode)){
                if(licenseCode.length() > 20){
                 errorRecord.append("<营业执照编码长度不能超过20位>");
                 isErrorRecord = false;
                }
               }
               //验证门店面积
               if(StringUtils.isNotBlank(storeArea)){
                if(storeArea.length() > 20){
                 errorRecord.append("<门店面积长度不能超过20位>");
                 isErrorRecord = false;
                }else if(!CheckUtil.isNumeric(storeArea)){
                 errorRecord.append("<门店面积必须是数字类型>");
                 isErrorRecord = false;
                }
               }
               //验证门店地址
               if(StringUtils.isNotBlank(storeAddr)){
                if(storeAddr.length() > 50){
                 errorRecord.append("<门店地址长度不能超过20位>");
                 isErrorRecord = false;
                }
               }
               //验证经营范围
               if(StringUtils.isNotBlank(businessScope)){
                if(businessScope.length() > 225){
                 errorRecord.append("<经营范围长度不能超过225位>");
                 isErrorRecord = false;
                }
               }
               //验证负责人
               if(StringUtils.isNotBlank(officerName)){
                if(officerName.length() > 10){
                 errorRecord.append("<负责人长度不能超过10位>");
                 isErrorRecord = false;
                }
               }
               //验证法人
               if(StringUtils.isNotBlank(legalPerson)){
                if(legalPerson.length() > 10){
                 errorRecord.append("<法人长度不能超过10位>");
                 isErrorRecord = false;
                }
               }
               //验证联系电话
               if(StringUtils.isNotBlank(phone)){
                if(!CheckUtil.checkTel(phone)){
                 errorRecord.append("<联系电话格式不正确,应该是11位手机号码或者11-12位固定电话>");
                 isErrorRecord = false;
                }
               }
               //验证备注
               if(StringUtils.isNotBlank(remark)){
                if(remark.length() > 500){
                 errorRecord.append("<备注长度不能超过500位>");
                 isErrorRecord = false;
                }
               }
               if(isErrorRecord){
                Store store = new Store();
                Area area = areaService.findAreaById(areaCode);
                store.setArea(area);
                store.setBusinessScope(businessScope);
                store.setCreateUserId(userInfo.getUserId()+"");
                store.setInsertTime(new Timestamp(System.currentTimeMillis()));
                store.setIsDelete(0);
                store.setLegalPerson(legalPerson);
                store.setLicenseCode(licenseCode);
                store.setOfficerName(officerName);
                store.setPhone(phone);
                store.setRemark(remark);
                store.setStoreArea(storeArea);
                store.setStoreAddr(storeAddr);
                store.setStoreName(storeName);
                storeService.saveOrUpdate(store);
                importSuccessNum ++;
               }else{
                storeVo.setImportErrorRecord(errorRecord.toString());
                erroStoreVoList.add(storeVo);
               }
              }
              
             }
             String path = this.getRequest().getContextPath();
                String basePath = getRequest().getScheme() + "://" + getRequest().getServerName() + ":" + getRequest().getServerPort() + path + "/";
             if(erroStoreVoList != null && erroStoreVoList.size() > 0){
              errorFile= exportResult();
              result = "导入成功"+importSuccessNum+"条记录,"+erroStoreVoList.size()+"记录导入失败,请您<a href='"+basePath+"/tempfiles/"+errorFile+"'><font color='blue'>点击下载失败文件</font>"+"</a>";
             }else{
              result = "导入成功!";
             }
             ajax(result);
            }
        }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            ajax("对不起!导入文件时出错!");
        }
        return null;
    }
    
    /**
     * 导出结果
     */
    private String exportResult()
    {
        String fileName="";
        try
        {
           if(erroStoreVoList!=null && erroStoreVoList.size()>0)
           {
                     //表头
               List<String> headList=new ArrayList<String>();
               headList.add("序号");
               headList.add("所属辖区");
               headList.add("门店名称");
               headList.add("营业执照编码");
               headList.add("门店面积");
               headList.add("门店地址");
               headList.add("法人");
               headList.add("负责人");
               headList.add("负责人电话");
               headList.add("经营范围");
               headList.add("备注");
               headList.add("失败原因");
               List<Map<String, Object>> mapList=new ArrayList<Map<String, Object>>();  //表内容
               Map<String, Object> map=null;
               int no = 1;
               for(StoreVo storeVo:erroStoreVoList)
               {
                   map=new HashMap<String, java.lang.Object>();
                   map.put("no",no++);
                   map.put("areaName",storeVo.getAreaName());
                   map.put("storeName",storeVo.getStoreName());
                   map.put("licenseCode",storeVo.getLicenseCode());
                   map.put("storeArea",storeVo.getStoreArea());
                   map.put("storeAddr",storeVo.getStoreAddr());
                   map.put("legalPerson",storeVo.getLegalPerson());
                   map.put("officerName",storeVo.getOfficerName());
                   map.put("phone",storeVo.getPhone());
                   map.put("businessScope",storeVo.getBusinessScope());
                   map.put("remark",storeVo.getRemark());
                   map.put("failureReason",storeVo.getImportErrorRecord());
                   mapList.add(map);
               }
               List<String> keyList=new ArrayList<String>();   //map的key
               keyList.add("no");//序号
               keyList.add("areaName");//所属辖区
               keyList.add("storeName");//门店名称
               keyList.add("licenseCode");//营业执照编码
               keyList.add("storeArea");//门店面积
               keyList.add("storeAddr");//门店地址
               keyList.add("legalPerson"); //法人
               keyList.add("officerName");//负责人
               keyList.add("phone");//负责人电话
               keyList.add("businessScope");//负责人电话
               keyList.add("remark");//负责人电话
               keyList.add("failureReason");//导入错误提示记录
               fileName=UUID.randomUUID().toString()+".xls";
               String path = ServletActionContext.getRequest().getRealPath("/tempfiles");
               File checkPath = new File(path);
               if (!checkPath.exists()) {
                   //目录不存在,则创建目录
                   checkPath.mkdirs();
               }
               if (!checkPath.exists()) {
                   //目录不存在,则创建目录
                   checkPath.mkdirs();
               }
               OutputStream os = new FileOutputStream(path+"/"+fileName);
               ExportExcel export=new ExportExcel(os,headList,mapList,keyList);
               export.export();
           }
        }
        catch (Exception ex)
        {
            LOGGER.error(ex.getMessage());
            ex.printStackTrace();
        }
        return fileName;
    }
    
    
 /**
     * 上传文件
     */
    private boolean uploadFile() {
        String path = ServletActionContext.getRequest().getRealPath("/upload");
        File checkPath = new File(path);
        if (!checkPath.exists()) {
            //目录不存在,则创建目录
            boolean result = checkPath.mkdirs();
            if (!result){
                return false;
            }
        }
        try {
            if (fileToUpload != null) {
                String fileName = UUID.randomUUID().toString();
                String ext = ".xls";
                if (uploadFileName != null) {
                    ext = uploadFileName.substring(uploadFileName.lastIndexOf("."));
                }
                if (!ext.equals(".xls")) {
                    return false;
                }
                String saveFileName = fileName + ext;
                File savefile = new File(new File(path), saveFileName);
                if (!savefile.getParentFile().exists()){
                    boolean result = savefile.getParentFile().mkdirs();
                    if (!result){
                        return false;
                    }
                }
                    
                FileUtils.copyFile(fileToUpload, savefile);//拷贝文件
                file = path + "/" + saveFileName;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
 public File getFileToUpload() {
  return fileToUpload;
 }
 public void setFileToUpload(File fileToUpload) {
  this.fileToUpload = fileToUpload;
 }
 public String getUploadFileName() {
  return uploadFileName;
 }
 public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
 }
 public String getUploadContentType() {
  return uploadContentType;
 }
 public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
 }
 public String getFile() {
  return file;
 }
 public void setFile(String file) {
  this.file = file;
 }

 public List<StoreVo> getErroStoreVoList() {
  return erroStoreVoList;
 }
 public void setErroStoreVoList(List<StoreVo> erroStoreVoList) {
  this.erroStoreVoList = erroStoreVoList;
 }
 public String getErrorFile() {
  return errorFile;
 }
 public void setErrorFile(String errorFile) {
  this.errorFile = errorFile;
 }
 
 
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值