excel的读取以及下载

来源:互联网 发布:双喷网格布工艺优化 编辑:程序博客网 时间:2024/06/10 09:49
<PRE class=java name="code">package com.miaozhen.userMiner.utils;


/**
 * 用于处理下载excel时对数据格式化的处理
 * @author zhangdekun
 *
 */
public class ExcelCellFormat {


    private String numbericFormat = null;
    private String stringFormat = null;
    public String getNumbericFormat() {
        return numbericFormat;
    }
    public void setNumbericFormat(String numbericFormat) {
        this.numbericFormat = numbericFormat;
    }
    public String getStringFormat() {
        return stringFormat;
    }
    public void setStringFormat(String stringFormat) {
        this.stringFormat = stringFormat;
    }
    public double getNumericValue(Object value){
        //TODO cell的格式化还没有做
        return Double.parseDouble(value.toString());
    }
    public String getStringValue(Object value){
        //TODO cell的格式化还没有做
        return value.toString();
    }
}
</PRE><PRE class=java name="code">package com.miaozhen.userMiner.utils;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
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;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class Excelbook {
    private static Logger logger = Logger.getLogger(Excelbook.class);
    private static final String XLS = "xls";
    private static final String XLSX = "xlsx";
    private static final String SEPERATOR = "_";


    private Map<String, CellStyle> styleMap = new HashMap<String,CellStyle>();// key为单元格的行列位置组成 (SEPERATOR)
    private Map<String, ExcelCellFormat> cellFormatMap = new HashMap<String,ExcelCellFormat>();


    public void setExcelStyle(Map<String, CellStyle> map) {
        if(map !=null){
            this.styleMap = map;
        }
    }


    public void setExcelCellFormat(Map<String,ExcelCellFormat> map){
        if(map !=null){
            this.cellFormatMap = map;
        }
    }
    /**
     * 获得文件的扩展名
     * 
     * @param fileName
     * @return
     */
    private String getExtension(String fileName) {
        return fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    /**
     * 将数据装载到excel
     * 
     * @param datas
     * @param fileName
     *            excel名称
     * @return
     */
    public byte[] buildExcel(List<Map<Integer, Object>> datas, String fileName) {
        String extension = getExtension(fileName);
        byte[] result = null;
        Workbook book = null;
        if (XLS.equals(extension)) {
            HSSFWorkbook hbook = new HSSFWorkbook();
            fill2003Excel(hbook, datas);
            book = hbook;
        } else if (XLSX.equals(extension)) {
            XSSFWorkbook xbook = new XSSFWorkbook();
            fill2007Excel(xbook, datas);
            book = xbook;
        } else {
            logger.info("不支持此种文件类型的下载(" + extension + ")");
        }
        if (null != book) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                book.write(baos);
                result = baos.toByteArray();
            } catch (IOException e) {
                logger.info(e.getMessage());
            } finally {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    private void fillCell(Object value, Cell cell, int row, int col) {
        // 设置单元格样式
        CellStyle cellStyle = this.styleMap.get(row + SEPERATOR + col);
        if (null != cellStyle) {
            cell.setCellStyle(cellStyle);
        }
        // 填充数据
        if (null != value) {
            ExcelCellFormat format = this.cellFormatMap.get(row + SEPERATOR + col);
            format = format==null?new ExcelCellFormat():format;
            if (StringUtils.isNumeric(value.toString())) {// 数值
                cell.setCellValue(format.getNumericValue(value));
            }else{
                cell.setCellValue(format.getStringValue(value));
            }
        }
    }


    /**
     * 下载为2003的excel
     * 
     * @param book
     * @param datas
     */
    private void fill2003Excel(HSSFWorkbook book, List<Map<Integer, Object>> datas) {
        HSSFSheet sheet = book.createSheet();
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                HSSFRow row = sheet.createRow(i);
                Map<Integer, Object> cellMap = datas.get(i);
                if(cellMap==null){
                    continue;
                }
                for (Map.Entry<Integer, Object> entry : cellMap.entrySet()) {
                    HSSFCell cell = row.createCell(entry.getKey());
                    fillCell(entry.getValue(), cell, i, entry.getKey());
                }
            }
        }
    }


    /**
     * 下载为2007的excel
     * 
     * @param book
     * @param datas
     */
    private void fill2007Excel(XSSFWorkbook book, List<Map<Integer, Object>> datas) {
        XSSFSheet sheet = book.createSheet();
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                XSSFRow row = sheet.createRow(i);
                Map<Integer, Object> cellMap = datas.get(i);
                if(cellMap==null){
                    continue;
                }
                for (Map.Entry<Integer, Object> entry : cellMap.entrySet()) {
                    XSSFCell cell = row.createCell(entry.getKey());
                    fillCell(entry.getValue(), cell, i, entry.getKey());
                }
            }
        }
    }
    /**
     * 读取excel
     * @param is
     * @param fileName
     * @return
     */
    public List<Map<Integer, Object>> readExcel(InputStream is,String fileName) {
        String extension = getExtension(fileName);// 文件扩展名
        if (XLS.equals(extension)) {
            return read2003Excel(is);
        } else if (XLSX.equals(extension)) {
            return read2007Excel(is);
        } else {
            logger.info("不支持的文件类型");
            return null;
        }
    }
    /**
     * 读取excel
     * 
     * @param file
     * @return 以excel中的行为一条记录
     */
    public List<Map<Integer, Object>> readExcel(File file) {
        String fileName = file.getName();
        String extension = getExtension(fileName);// 文件扩展名
        if (XLS.equals(extension)) {
            return read2003Excel(file);
        } else if (XLSX.equals(extension)) {
            return read2007Excel(file);
        } else {
            logger.info("不支持的文件类型");
            return null;
        }
    }


    /**
     * 获得一个单元格的数据
     * 
     * @param cell
     * @param i
     * @param j
     * @return
     */
    private Object getCellValue(Cell cell, int i, int j) {
        Object value = null;
        if (null != cell) {
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    value = cell.getDateCellValue();
                } else {
                    value = cell.getNumericCellValue();
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                logger.info("此excel数据类型无法处理,row=" + (i + 1) + "col=" + (j + 1) + "value=" + cell.toString());
            }
        }
        return value;
    }
    /**
     * 读取2003excel
     * @param is
     * @return
     */
    private List<Map<Integer, Object>> read2003Excel(InputStream is) {
        List<Map<Integer, Object>> resultList = new ArrayList<Map<Integer, Object>>();
        try {
            HSSFWorkbook hwb = new HSSFWorkbook(is);
            HSSFSheet sheet = hwb.getSheetAt(0);
            Object value = null;
            HSSFRow row = null;
            HSSFCell cell = null;
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Map<Integer, Object> record = null;
                row = sheet.getRow(i);
                if (null != row) {
                    record = new LinkedHashMap<Integer, Object>();
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        cell = row.getCell(j);
                        value = getCellValue(cell, i, j);
                        record.put(j, value);
                    }
                }
                resultList.add(record);
            }
        } catch (IOException e) {
            logger.info(e.getMessage());
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultList;
    }
    /**
     * 读取2003 excel
     * 
     * @param file
     * @return
     */
    private List<Map<Integer, Object>> read2003Excel(File file) {
        List<Map<Integer, Object>> resultList = new ArrayList<Map<Integer, Object>>();
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.info(file.getName() + " is not exist");
            e.printStackTrace();
        }
        if(null !=fs){
            resultList = read2003Excel(fs);
        }
        return resultList;
    }
    /**
     * 读取2007 excel
     * @param is
     * @return
     */
    private List<Map<Integer, Object>> read2007Excel(InputStream is) {
        List<Map<Integer, Object>> resultList = new ArrayList<Map<Integer, Object>>();
        try {
            XSSFWorkbook xwb = new XSSFWorkbook(is);
            XSSFSheet sheet = xwb.getSheetAt(0);
            Object value = null;
            XSSFRow row = null;
            XSSFCell cell = null;
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Map<Integer, Object> record = null;
                row = sheet.getRow(i);
                if (null != row) {
                    record = new LinkedHashMap<Integer, Object>();
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        cell = row.getCell(j);
                        value = getCellValue(cell, i, j);
                        record.put(j, value);
                    }
                }
                resultList.add(record);
            }
        }  catch (IOException e) {
            logger.info(e.getMessage());
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultList;
    }
    /**
     * 读取2007 excel
     * 
     * @param file
     * @return
     */
    private List<Map<Integer, Object>> read2007Excel(File file) {
        List<Map<Integer, Object>> resultList = new ArrayList<Map<Integer, Object>>();
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.info(file.getName() + " is not exist");
            e.printStackTrace();
        }
        if(null !=fs){
            resultList = read2007Excel(fs);
        }
        return resultList;
    }
}
</PRE><BR>
<PRE class=java name="code">package com.miaozhen.userMiner.utils;


import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;


import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


/**
 * 导出excel
 * @author zhangdekun
 *
 */
public class DownloadExcel  {
    private Logger logger = Logger.getLogger(DownloadExcel.class);
    private String fileName;
    private List<Map<Integer,Object>> datas;
    
    public String getFileName() {
        return fileName;
    }


    public void setFileName(String fileName) {
        this.fileName = fileName;
    }


    public List<Map<Integer, Object>> getDatas() {
        return datas;
    }


    public void setDatas(List<Map<Integer, Object>> datas) {
        this.datas = datas;
    }


    public void downLoad(HttpServletRequest request,HttpServletResponse response) {
            Excelbook book = new Excelbook();
            OutputStream os = null;
            try {
                os = response.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            response.reset();//清空输出流
            String fName = this.encodeFilename(request);
            response.setHeader("Content-disposition", "attachment;filename="+fName);
            response.setContentType("application/x-download");
            byte[] dataBytes = book.buildExcel(datas, fName);
            try {
                os.write(dataBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(null !=os){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        
    }


    /** 
     * 设置下载文件的中文名称
     *  
     * @param filename 
     * @param request 
     * @return 
     */  
    private String encodeFilename(HttpServletRequest request) {  
      /** 
       * 获取客户端浏览器和操作系统信息
       * 在ie浏览器中得到的是User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar) 
       * 在firefox中得到的是User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6 
       */  
      String agent = request.getHeader("USER-AGENT");  
      String filename = this.fileName;
      if(filename==null){
          filename = new Date() + ".xlsx";//默认一个excel文件名
      }
      try {  
        if ((agent != null) && (-1 != agent.indexOf("MSIE"))) {  
          String newFileName = URLEncoder.encode(filename, "UTF-8");  
          newFileName = StringUtils.replace(newFileName, "+", "%20");  
          if (newFileName.length() > 150) {  
            newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1");  
            newFileName = StringUtils.replace(newFileName, " ", "%20");  
          }  
          return newFileName;  
        }  
        if ((agent != null) && (-1 != agent.indexOf("Mozilla")))  
          return MimeUtility.encodeText(filename, "UTF-8", "B");  
    
        return filename;  
      } catch (Exception ex) {  
        return filename;  
      }  
    } 
}
</PRE><BR>
<BR>
<BR>

<PRE></PRE>


参考:http://blog.csdn.net/zhangdekun222/article/details/8598201

原创粉丝点击