码迷,mamicode.com
首页 > 编程语言 > 详细

4java excel导出导入

时间:2016-08-02 01:13:16      阅读:677      评论:0      收藏:0      [点我收藏+]

标签:

package com.reset.weiyunjinfu.controller.system.appuser;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.reset.weiyunjinfu.util.FileDownload;
import com.reset.weiyunjinfu.util.PathUtil;
import com.reset.weiyunjinfu.util.SMSUtils;
import com.reset.weiyunjinfu.util.StringUtil;
import com.reset.weiyunjinfu.common.bean.Code;
import com.reset.weiyunjinfu.common.bean.Result;
import com.reset.weiyunjinfu.controller.base.BaseController;
import com.reset.weiyunjinfu.entity.Page;
import com.reset.weiyunjinfu.entity.system.Role;
import com.reset.weiyunjinfu.entity.system.User;
import com.reset.weiyunjinfu.framework.ActionControllerLog;
import com.reset.weiyunjinfu.service.system.appuser.AccessoryService;
import com.reset.weiyunjinfu.service.system.appuser.AppuserService;
import com.reset.weiyunjinfu.service.system.appuser.CarService;
import com.reset.weiyunjinfu.service.system.appuser.HouseService;
import com.reset.weiyunjinfu.service.system.appuser.LoanService;
import com.reset.weiyunjinfu.service.system.role.RoleService;
import com.reset.weiyunjinfu.util.AppUtil;
import com.reset.weiyunjinfu.util.Const;
import com.reset.weiyunjinfu.util.DesMgr;
import com.reset.weiyunjinfu.util.FileUpload;
import com.reset.weiyunjinfu.util.GetPinyin;
import com.reset.weiyunjinfu.util.Jurisdiction;
import com.reset.weiyunjinfu.util.MD5;
import com.reset.weiyunjinfu.util.ObjectExcelRead;
import com.reset.weiyunjinfu.util.ObjectExcelView;
import com.reset.weiyunjinfu.util.PageData;
import com.reset.weiyunjinfu.util.SystemConfigUtil;
import com.reset.weiyunjinfu.util.Tools;
 
@Controller
@RequestMapping(value="/happuser")
public class AppuserController extends BaseController {
    
    String menuUrl = "happuser/listUsers.do"; //菜单地址(权限用)
    @Resource(name="appuserService")
    private AppuserService appuserService;
    @Resource(name="roleService")
    private RoleService roleService;
    @Resource(name="houseService")
    private HouseService houseService;
    @Resource(name="carService")
    private CarService carService;
    @Resource(name="accessoryService")
    private AccessoryService accessoryService;
    @Resource(name="loanService")
    private LoanService loanService;
   
    
    /*
     * 导出会员信息到excel
     * @return
     */
    @RequestMapping(value="/excel")
    public ModelAndView exportExcel(){
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try{
            if(Jurisdiction.buttonJurisdiction(menuUrl, "cha")){    
                //检索条件===
                String USERNAME = pd.getString("USERNAME");
                if(null != USERNAME && !"".equals(USERNAME)){
                    USERNAME = USERNAME.trim();
                    pd.put("USERNAME", USERNAME);
                }
                String lastLoginStart = pd.getString("lastLoginStart");
                String lastLoginEnd = pd.getString("lastLoginEnd");
                if(lastLoginStart != null && !"".equals(lastLoginStart)){
                    lastLoginStart = lastLoginStart+" 00:00:00";
                    pd.put("lastLoginStart", lastLoginStart);
                }
                if(lastLoginEnd != null && !"".equals(lastLoginEnd)){
                    lastLoginEnd = lastLoginEnd+" 00:00:00";
                    pd.put("lastLoginEnd", lastLoginEnd);
                } 
                //检索条件===
                
                Map<String,Object> dataMap = new HashMap<String,Object>();
                List<String> titles = new ArrayList<String>();
                
                titles.add("用户名");         //1
                titles.add("编号");          //2
                titles.add("姓名");            //3
                titles.add("手机号");        //4
                titles.add("身份证号");        //5
                titles.add("等级");            //6
                titles.add("邮箱");            //7
                titles.add("最近登录");        //8
                titles.add("到期时间");        //9
                titles.add("上次登录IP");    //10
                
                dataMap.put("titles", titles);
                
                List<PageData> userList = appuserService.listAllUser(pd);
                List<PageData> varList = new ArrayList<PageData>();
                for(int i=0;i<userList.size();i++){
                    PageData vpd = new PageData();
                    vpd.put("var1", userList.get(i).getString("USERNAME"));        //1
                    vpd.put("var2", userList.get(i).getString("NUMBER"));        //2
                    vpd.put("var3", userList.get(i).getString("NAME"));            //3
                    vpd.put("var4", userList.get(i).getString("PHONE"));        //4
                    vpd.put("var5", userList.get(i).getString("SFID"));            //5
                    vpd.put("var6", userList.get(i).getString("ROLE_NAME"));    //6
                    vpd.put("var7", userList.get(i).getString("EMAIL"));        //7
                    vpd.put("var8", userList.get(i).getString("LAST_LOGIN"));    //8
                    vpd.put("var9", userList.get(i).getString("END_TIME"));        //9
                    vpd.put("var10", userList.get(i).getString("IP"));            //10
                    varList.add(vpd);
                }
                
                dataMap.put("varList", varList);
                
                ObjectExcelView erv = new ObjectExcelView();
                mv = new ModelAndView(erv,dataMap);
            }
        } catch(Exception e){
            logger.error(e.toString(), e);
        }
        return mv;
    }
    /**
     * 打开上传EXCEL页面
     */
    @RequestMapping(value="/goUploadExcel")
    public ModelAndView goUploadExcel()throws Exception{
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("system/appuser/uploadexcel");
        return mv;
    }
    /**
     * 从EXCEL导入到数据库
     */
    @RequestMapping(value="/readExcel")
    public void readExcel(
            @RequestParam(value="excel",required=false) MultipartFile file,HttpServletResponse response
            ) throws Exception{
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return ;}
        String rt="";
        if (null != file && !file.isEmpty()) {
            String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;                                //文件上传路径
            String fileName =  FileUpload.fileUp(file, filePath, "userexcel");                            //执行上传
            
            List<PageData> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 1, 0, 0);    //执行读EXCEL操作,读出的数据导入List 2:从第3行开始;0:从第A列开始;0:第0个sheet
            
            rt=appuserService.saveExcel(listPd, pd);
            
            mv.addObject("msg",rt);
        }
        String path = getRequest().getContextPath();
        String basePath = getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+path+"/";
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("<script> alert(‘"+rt+"‘);location.href=‘"+basePath+"happuser/goUploadExcel‘;</script>");
    }
    //===================================================================================================
     
    /**
     * 下载模版
     */
    @RequestMapping(value="/downExcel")
    public void downExcel(HttpServletResponse response)throws Exception{
        
        FileDownload.fileDownload(response, PathUtil.getClasspath() + Const.FILEPATHFILE + "Users.xls", "Users.xls");
        
    }
    @InitBinder
    public void initBinder(WebDataBinder binder){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
    }
    
    /* ===============================权限================================== */
    public Map<String, String> getHC(){
        Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
    }
    /* ===============================权限================================== */
    
    /**
     * 下载模版
     */
    @RequestMapping(value="/downloadFile")
    @ResponseBody
    public void downExcel(HttpServletResponse response,String fileName,String userId)throws Exception{
        File imgFile = new File(SystemConfigUtil.getSystemConfig().getBaseFileUpload()+fileName);
        logger.info(imgFile.getPath());
        if(imgFile.exists()){            
            FileDownload.fileDownload(response,imgFile.getPath(), fileName);
        } 
        String path = getRequest().getContextPath();
        String basePath = getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+path+"/";
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("<script> alert(‘服务器找不到您的文件‘);location.href=‘"+basePath+"happuser/golook?USER_ID="+userId+"‘;</script>");
    }
}
package com.reset.weiyunjinfu.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传文件
 * 创建人:FH 创建时间:2014年12月23日
 * @version
 */
public class FileUpload {
    public static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
    /**
     * @param file             //文件对象
     * @param filePath        //上传路径
     * @param fileName        //文件名
     * @return  文件名
     */
    public static String fileUp(MultipartFile file, String filePath, String fileName){
        String extName = ""; // 扩展名格式:
        try {
            if (file.getOriginalFilename().lastIndexOf(".") >= 0){
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
        } catch (IOException e) {
            System.out.println(e);
        }
        return fileName+extName;
    }
    
    /**
     * 写文件到当前目录的upload目录中
     * 
     * @param in
     * @param fileName
     * @throws IOException
     */
    private static String copyFile(InputStream in, String dir, String realName)
            throws IOException {
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        FileUtils.copyInputStreamToFile(in, file);
        return realName;
    }
    

    public static Map<String, Object> uploadFile(MultipartFile file,
            String uploadPath,int width,int height) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String fileFix = file.getOriginalFilename().substring(
                file.getOriginalFilename().lastIndexOf("."),
                file.getOriginalFilename().length());
        String UUId = UUIDGenerator.getUUIDString();
        String dateDay = DateUtil.getDays();
        String filePath = uploadPath + dateDay + File.separator + UUId
                + fileFix;
        String UUID2 = UUIDGenerator.getUUIDString();
        String descPath = uploadPath + dateDay + File.separator + UUID2 + fileFix;
        File f = new File(filePath);
        File fp = f.getParentFile();
        if (!f.exists()) {
            fp.mkdirs();
            f.createNewFile();
        }
        file.transferTo(f);
        File fileType = new File(filePath);
        if (null == getImageFileType(fileType)) {
            fileType.delete();
            map.put("imgFlag", "-1");
        } else {
            boolean b = compress(filePath, descPath,width,height);
            if(b){
                map.put("imageUrl", dateDay + "/" + UUID2 + fileFix);
                fileType.delete();
            }else{
                map.put("imageUrl", dateDay + "/" + UUId + fileFix);
            }
            map.put("imgFlag", "0");
        }
        return map;

    }

    /**压缩图片
     * @param fileName
     * @param filePath
     * @return
     */
    public static boolean compress(String fileName,String filePath,int width,int height ){
        try {
            if(width >0 && height >0){
                ImgCompress imgCom = new ImgCompress(fileName,filePath);
                imgCom.resizeFix(width, height);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * <p>
     * Discription:[getImageFileType,获取图片文件实际类型,若不是图片则返回null]
     * </p>
     * 
     * @param File
     * @return fileType
     * @author:[shixing_11@sina.com]
     */
    public static String getImageFileType(File f) {
        if (isImage(f)) {
            try {
                ImageInputStream iis = ImageIO.createImageInputStream(f);
                Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
                if (!iter.hasNext()) {
                    return null;
                }
                ImageReader reader = iter.next();
                iis.close();
                return reader.getFormatName();
            } catch (IOException e) {
                return null;
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
    
    /**
     * <p>
     * Discription:[getAllFileType,常见文件头信息]
     * </p>
     * 
     * @author:[shixing_11@sina.com]
     */
    private static void getAllFileType() {
        FILE_TYPE_MAP.put("jpg", "FFD8FF"); // JPEG (jpg)
        FILE_TYPE_MAP.put("png", "89504E47"); // PNG (png)
        FILE_TYPE_MAP.put("gif", "47494638"); // GIF (gif)
        FILE_TYPE_MAP.put("tif", "49492A00"); // TIFF (tif)
        FILE_TYPE_MAP.put("bmp", "424D"); // Windows Bitmap (bmp)
        FILE_TYPE_MAP.put("dwg", "41433130"); // CAD (dwg)
        FILE_TYPE_MAP.put("html", "68746D6C3E"); // HTML (html)
        FILE_TYPE_MAP.put("rtf", "7B5C727466"); // Rich Text Format (rtf)
        FILE_TYPE_MAP.put("xml", "3C3F786D6C");
        FILE_TYPE_MAP.put("zip", "504B0304");
        FILE_TYPE_MAP.put("rar", "52617221");
        FILE_TYPE_MAP.put("psd", "38425053"); // Photoshop (psd)
        FILE_TYPE_MAP.put("eml", "44656C69766572792D646174653A"); // Email
                                                                    // [thorough
                                                                    // only]
                                                                    // (eml)
        FILE_TYPE_MAP.put("dbx", "CFAD12FEC5FD746F"); // Outlook Express (dbx)
        FILE_TYPE_MAP.put("pst", "2142444E"); // Outlook (pst)
        FILE_TYPE_MAP.put("xls", "D0CF11E0"); // MS Word
        FILE_TYPE_MAP.put("doc", "D0CF11E0"); // MS Excel 注意:word 和 excel的文件头一样
        FILE_TYPE_MAP.put("mdb", "5374616E64617264204A"); // MS Access (mdb)
        FILE_TYPE_MAP.put("wpd", "FF575043"); // WordPerfect (wpd)
        FILE_TYPE_MAP.put("eps", "252150532D41646F6265");
        FILE_TYPE_MAP.put("ps", "252150532D41646F6265");
        FILE_TYPE_MAP.put("pdf", "255044462D312E"); // Adobe Acrobat (pdf)
        FILE_TYPE_MAP.put("qdf", "AC9EBD8F"); // Quicken (qdf)
        FILE_TYPE_MAP.put("pwl", "E3828596"); // Windows Password (pwl)
        FILE_TYPE_MAP.put("wav", "57415645"); // Wave (wav)
        FILE_TYPE_MAP.put("avi", "41564920");
        FILE_TYPE_MAP.put("ram", "2E7261FD"); // Real Audio (ram)
        FILE_TYPE_MAP.put("rm", "2E524D46"); // Real Media (rm)
        FILE_TYPE_MAP.put("mpg", "000001BA"); //
        FILE_TYPE_MAP.put("mov", "6D6F6F76"); // Quicktime (mov)
        FILE_TYPE_MAP.put("asf", "3026B2758E66CF11"); // Windows Media (asf)
        FILE_TYPE_MAP.put("mid", "4D546864"); // MIDI (mid)
    }

    /**
     * <p>
     * Discription:[isImage,判断文件是否为图片]
     * </p>
     * 
     * @param file
     * @return true 是 | false 否
     * @author:[shixing_11@sina.com]
     */
    public static boolean isImage(File file) {
        boolean flag = false;
        try {
            BufferedImage bufreader = ImageIO.read(file);
            int width = bufreader.getWidth();
            int height = bufreader.getHeight();
            if (width == 0 || height == 0) {
                flag = false;
            } else {
                flag = true;
            }
        } catch (IOException e) {
            flag = false;
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
}
package com.reset.weiyunjinfu.util;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


/**
 * 从EXCEL导入到数据库
 * 创建人:FH 创建时间:2014年12月23日
 * @version
 */
public class ObjectExcelRead {

    /**
     * @param filepath //文件路径
     * @param filename //文件名
     * @param startrow //开始行号
     * @param startcol //开始列号
     * @param sheetnum //sheet
     * @return list
     */
    public static List<Object> readExcel(String filepath, String filename, int startrow, int startcol, int sheetnum) {
        List<Object> varList = new ArrayList<Object>();

        try {
            File target = new File(filepath, filename);
            FileInputStream fi = new FileInputStream(target);
            HSSFWorkbook wb = new HSSFWorkbook(fi);
            HSSFSheet sheet = wb.getSheetAt(sheetnum);                     //sheet 从0开始
            int rowNum = sheet.getLastRowNum() + 1;                     //取得最后一行的行号

            for (int i = startrow; i < rowNum; i++) {                    //行循环开始
                
                PageData varpd = new PageData();
                HSSFRow row = sheet.getRow(i);                             //
                int cellNum = row.getLastCellNum();                     //每行的最后一个单元格位置
                
                for (int j = startcol; j < cellNum; j++) {                //列循环开始
                    
                    HSSFCell cell = row.getCell(Short.parseShort(j + ""));
                    String cellValue = null;
                    if (null != cell) {
                        switch (cell.getCellType()) {                     // 判断excel单元格内容的格式,并对其进行转换,以便插入数据库
                        case 0:
                            cellValue = String.valueOf(cell.getNumericCellValue());
                            BigDecimal db = new BigDecimal(cellValue);
                            cellValue = db.toPlainString();
                            break;
                        case 1:
                            cellValue = cell.getStringCellValue();
                            break;
                        case 2:
                            cellValue = cell.getNumericCellValue() + "";
                            // cellValue = String.valueOf(cell.getDateCellValue());
                            break;
                        case 3:
                            cellValue = "";
                            break;
                        case 4:
                            cellValue = String.valueOf(cell.getBooleanCellValue());
                            break;
                        case 5:
                            cellValue = String.valueOf(cell.getErrorCellValue());
                            break;
                        }
                    } else {
                        cellValue = "";
                    }
                    
                    varpd.put("var"+j, cellValue);
                    
                }
                varList.add(varpd);
            }

        } catch (Exception e) {
            System.out.println(e);
        }
        
        return varList;
    }
}
package com.reset.weiyunjinfu.util;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;


/**
 * 下载文件
 * 创建人:FH 创建时间:2014年12月23日
 * @version
 */
public class FileDownload {

    /**
     * @param response 
     * @param filePath        //文件完整路径(包括文件名和扩展名)
     * @param fileName        //下载后看到的文件名
     * @return  文件名
     */
    public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{  
             
            byte[] data = FileUtil.toByteArray2(filePath);  
            fileName = URLEncoder.encode(fileName, "UTF-8");  
            response.reset();  
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
            response.addHeader("Content-Length", "" + data.length);  
            response.setContentType("application/octet-stream;charset=UTF-8");  
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
            outputStream.write(data);  
            outputStream.flush();  
            outputStream.close();
            response.flushBuffer();
            
        } 

}

 

4java excel导出导入

标签:

原文地址:http://www.cnblogs.com/zxayxh1314/p/5727686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!