ExcelUtils上傳下載

一.下載

public void Downloads(HttpServletResponse response , String url){
    try {
        
        File file = new File(url);
        String str = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String name=str+".xlsx";
        if(file.exists()){ //判斷文件父目錄是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));
            response.setHeader("Pragma", URLEncoder.encode(name, "UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件輸入流
            BufferedInputStream bis = null;
            OutputStream os = null; //輸出流
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }
            bis.close();
            fis.close();
        }
    }catch (Exception e){
        e.printStackTrace();
        logger.warn("sys:zydownload:Downloads--userId:"+ ShiroUtils.getUserId()+"===="+e.getMessage());
    }
}

二,ExcelUtils工具類

package com.zy.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.zy.modules.sys.entity.SysUserEntity;
import com.zy.modules.sys.excel.ScAdminProxyBean;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
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.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

/**
 * excel工具類
 *
 * @author Mark [email protected]
 * @since 2018-03-24
 */
public class ExcelUtils {
    private static Logger logger = LoggerFactory.getLogger(com.zy.common.utils.ExcelUtils.class);
    /**
     * Excel導出
     *
     * @param response      response
     * @param fileName      文件名
     * @param list          數據List
     * @param pojoClass     對象Class
     */
    public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> list,
                                     Class<?> pojoClass) throws IOException {
        Workbook workbook = ExcelExportUtil.exportBigExcel(new ExportParams(), pojoClass, list);
      ExcelExportUtil.closeExportBigExcel();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        response.setHeader("Pragma", URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
    }

    public static void exportExcel( String fileName, Collection<?> list,
                                    Class<?> pojoClass) throws IOException {
        FileOutputStream fouts = new FileOutputStream(fileName);
        Workbook workbook = ExcelExportUtil.exportBigExcel(new ExportParams(), pojoClass, list);
        ExcelExportUtil.closeExportBigExcel();
        workbook.write(fouts);
        fouts.flush();
        fouts.close();
    }

    /**
     * Excel導出,先sourceList轉換成List<targetClass>,再導出
     *
     * @param response      response
     * @param fileName      文件名
     * @param sourceList    原數據List
     * @param targetClass   目標對象Class
     */
    public static void exportExcelToTarget(HttpServletResponse response, String fileName, Collection<?> sourceList,
                                     Class<?> targetClass) throws Exception {
        List targetList = new ArrayList<>(sourceList.size());
        for(Object source : sourceList){
            Object target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);
            targetList.add(target);
        }

        exportExcel(response, fileName, targetList, targetClass);
    }

    


    /**
     * Excel導出,先sourceList轉換成List<targetClass>,再導出
     ** @param fileName      文件名
     * @param sourceList    原數據List
     * @param targetClass   目標對象Class
     */
    public static void exportExcelToTarget3(String fileName, Collection<?> sourceList,
                                           Class<?> targetClass) throws Exception {
        List targetList = new ArrayList<>(sourceList.size());
        for(Object source : sourceList){
            Object target = targetClass.newInstance();
            BeanUtils.copyProperties(source, target);
            targetList.add(target);
        }

        exportExcel(fileName, targetList, targetClass);
    }


    /**
     * 解析excel
     * @param file
     * @return
     */
    public static List<String[]> parseExcel(File file){
        //獲得Workbook工作薄對象
        Workbook wb=getWorkbook(file);

        List<String[]> list=new ArrayList<>();
        if(wb == null){
            logger.error("不支持的文件類型");
            return null;
        }

        for (int sheetNum = 0;sheetNum<wb.getNumberOfSheets();sheetNum++){
            //獲得當前sheet工作表
            Sheet sheet = wb.getSheetAt(sheetNum);
            if (sheet==null){
                continue;
            }
            //獲得當前sheet的開始行
            int firstRowNum = sheet.getFirstRowNum();
            //獲得當前sheet的結束行
            int lastRowNum = sheet.getLastRowNum();
            //跳過第一行
            for(int i = firstRowNum+1;i<=lastRowNum;i++){
                Row row= sheet.getRow(i);
                if (row==null){
                    continue;
                }
                //開始列
                int firstCellNum = row.getFirstCellNum();
                //結束列
                int lastCellNum = row.getLastCellNum();

                String[] cells=new String[lastCellNum];
                for (int j = firstCellNum; j <lastCellNum ; j++) {
                    Cell cell =row.getCell(j);
                    cells[j]=getCellValue(cell);
                }
                list.add(cells);
            }
        }
        return list;
    }

    /**
     * 解析數據格式
     * @param cell
     * @return
     */
    private static String getCellValue(Cell cell){
        if (cell == null) {
            return "";
        }
        switch (cell.getCellTypeEnum()) {
            case NUMERIC:
                //cell.setCellType(Cell.CELL_TYPE_STRING);
                DecimalFormat df = new DecimalFormat("0");

                return String.valueOf(df.format(cell.getNumericCellValue()));
            case STRING:
                return String.valueOf(cell.getStringCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return String.valueOf(cell.getCellFormula());
            case BLANK:
                return "";
            case ERROR:
                return "非法字符";
            default:
                return "未知類型";
        }
    }

    private static Workbook getWorkbook(File file)  {
        try(InputStream in = new FileInputStream(file)){
            String fileName = file.getName();
            if(fileName.endsWith(".xls")){
                return new HSSFWorkbook(new BufferedInputStream(in));
            }else if (fileName.endsWith(".xlsx")){
                return new XSSFWorkbook(new BufferedInputStream(in));
            }else if (fileName.endsWith(".csv")){
                return null;
            }
        } catch (IOException e) {
            logger.error("Excel文件解析出錯",e);
        }
        return null;

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章