Java导出多个Sheet的Excel,并上传到Ftp

Java导出多个Sheet的Execl,并上传到Ftp

一、pom.xml 引入需要的依赖


    
        org.apache.poi
        poi
        3.10-FINAL
     
     
        org.apache.poi
        poi-ooxml
        3.10-FINAL
     

二、创建Execl 工具处理类ExcelSheetsUtil

import com.eiot.e_view.utils.common.ImageUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ExcelSheetsUtil {
    /**
     * 设置正文单元样式
     *
     * @param workbook
     * @return
     */
    public static HSSFCellStyle createBodyCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 8);
        font.setFontName(HSSFFont.FONT_ARIAL);//设置标题字体
        cellStyle.setFont(font);
        cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
        return cellStyle;
    }

    /**
     * 设置正文单元时间样式
     *
     * @param workbook
     * @return
     */
    public static HSSFCellStyle createDateBodyCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 8);
        font.setFontName(HSSFFont.FONT_ARIAL);//设置标题字体
        cellStyle.setFont(font);
        cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
        HSSFDataFormat format = workbook.createDataFormat();
        cellStyle.setDataFormat(format.getFormat("yyyy-mm-dd"));
        return cellStyle;
    }

    /**
     * 设置标题单元样式
     *
     * @param workbook
     * @return
     */
    public static HSSFCellStyle createTitleCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        HSSFFont font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        font.setFontHeightInPoints((short) 8);
        font.setFontName(HSSFFont.FONT_ARIAL);//设置标题字体
        cellStyle.setFont(font);
        cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);//设置列标题样式
        cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);// 设置背景色
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
        return cellStyle;
    }

    /**
     * 写入标题行
     *
     * @param sheet
     * @param cellStyle
     * @param cellValues 标题数组
     * @return
     */
    public static void writeTitleContent(HSSFSheet sheet, HSSFCellStyle cellStyle, String[] cellValues) {

        HSSFRow row = null;
        HSSFCell cell = null;
        //标题
        row = sheet.createRow(0);
        //第一行写入标题行
        for (int i = 0; i < cellValues.length; i++) {
            cell = row.createCell((short) i);//序号
            cell.setCellStyle(cellStyle);
            cell.setCellValue(cellValues[i]);
        }
    }

    /**
     * 设置列宽
     *
     * @param sheet
     */
    public static void setSheetColumn(HSSFSheet sheet) {
        sheet.setColumnWidth((short) 2, (short) 3200);//设置列宽
        sheet.setColumnWidth((short) 4, (short) 3200);
        sheet.setColumnWidth((short) 7, (short) 5250);
        sheet.setColumnWidth((short) 8, (short) 6250);
    }
	/**
	 * 数据导入Excle 中
	 * @param sheetNameList sheet 名字集合
	 * @param dataMap 数据域
	 * @param cellValues  标题名字
	 * @return
	 */
    public static String dataToExcel(List sheetNameList, Map>> dataMap, String[] cellValues) {
        HSSFWorkbook workbook = new HSSFWorkbook();//创建excel
        ByteArrayOutputStream ops = null;
        ByteArrayInputStream in = null;
        HSSFRow row = null;//创建一行
        HSSFCell cell = null;//每个单元格
        HSSFSheet sheet = null;
        String filePath = "";
        for (String sheetName : sheetNameList) {
            List> valueList = dataMap.get(sheetName);
            sheet = null;
            int bodyRowCount = 1;//正文内容行号
            sheet = workbook.createSheet(sheetName);//创建一个工作薄
            ExcelSheetsUtil.setSheetColumn(sheet);//设置工作薄列宽
            HSSFCellStyle titleCellStyle = ExcelSheetsUtil.createTitleCellStyle(workbook);
            ExcelSheetsUtil.writeTitleContent(sheet, titleCellStyle, cellValues); //写入标题
            //正文内容
            for (List item : valueList) {
                row = sheet.createRow(bodyRowCount++);
                //第二行写开始写入正文内容
                for (int i = 0; i < cellValues.length; i++) {
                    cell = row.createCell((short) i);
                    cell.setCellValue(item.get(i));
                }
            }
        }
        ops = new ByteArrayOutputStream();
        try {
            workbook.write(ops);
            byte[] b = ops.toByteArray();
            in = new ByteArrayInputStream(b);
            // 请求Ftp,文件上传
            filePath = ImageUtil.uploadExeclFile(in, new Date().getTime() + "execl.xlsx"); 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ops.flush();
                ops.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }
} 

三、ftp 上传文件流

public static String uploadExeclFile(InputStream inputStream,String fileName) {
    //获取文件的格式
    String fileType = fileName.substring(fileName.indexOf(".")).toLowerCase().trim();
    //生成一个随机的文件名,避免重名覆盖
    String randomString = UUID.randomUUID().toString().replaceAll("-", "");
    String fileNewName = randomString + fileType;
    FTPClient ftpClient = new FTPClient();
    try {
        /*
         *  主动模式 enterLocalActiveMode()->
         *  FTP客户端连接到FTP服务器的21端口,发送用户名和密码登录,登录成功后要list列表或者读取数据时,客户端随机开放一个端口(1024以上),发送 PORT命令到FTP服务器,告诉服务器客户端采用主动模式并开放端口;
         *  FTP服务器收到PORT主动模式命令和端口号后,通过服务器的20端口和客户端开放的端口连接,发送数据
         *  被动模式enterLocalPassiveMode()->
         *  FTP客户端连接到FTP服务器的21端口,发送用户名和密码登录,登录成功后要list列表或者读取数据时,发送PASV命令到FTP服务器, 服务器在本地随机开放一个端口(1024以上),
         *  然后把开放的端口告诉客户端, 客户端再连接到服务器开放的端口进行数据传输
         * */
        // ftpClient.enterLocalActiveMode();    //主动模式
        ftpClient.connect(EViewConstant.FtpFileServer.HOST, EViewConstant.FtpFileServer.PORT);
        ftpClient.login(EViewConstant.FtpFileServer.USER_NAME, EViewConstant.FtpFileServer.PASSWORD);

        //ftp上传文件是以文本形式传输的,所以多媒体文件会失真,需要转为二进制形式传输
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            log.error("未连接到FTP,用户名或密码错误。");
            ftpClient.disconnect();
        } else {
            log.info("FTP连接成功");
        }
        long start = System.currentTimeMillis();
        ftpClient.setControlEncoding("UTF-8");
        //设置成被动模式
        ftpClient.enterLocalPassiveMode();
        boolean fig = ftpClient.storeFile(fileNewName, inputStream);
        if (fig) {
            long end = System.currentTimeMillis();
            log.info(String.format("文件:%s上传成功,耗时:%d毫秒", fileNewName, (end - start)));
        } else {
            log.error("上传失败;ftpClient.storeFile()返回false");
            return "";
        }
    } catch (IOException io) {
        io.printStackTrace();
        log.error("保存Execl到文件服务器ERROR:" + io.getMessage());
        return "";
    } finally {
        //关闭资源
        try {
            if (null != inputStream) {
                inputStream.close();
            }
            //退出
            ftpClient.logout();
            //断开连接
            ftpClient.disconnect();
        } catch (IOException io) {
            log.error("保存Execl到文件服务器关闭资源ERROR" + io.getMessage());
        }
    }
    return EViewConstant.FtpFileServer.IMAGE_URL + fileNewName;
}

四、调用演示

/**
 * 井盖下线缆历史数据导出
 *
 * @param req
 * @return
 */
@Override
public BaseDataRespDTO LineDataListToExcel(DataQueryReq req) {
    // 获取线缆历史数据
    DataLineResultVO lineDataResultVO = this.getLineDataList(req);
    List lineInfoList = lineDataResultVO.getLineInfoList();
    Map> lineDateMap = lineDataResultVO.getLineDateMap();
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    int bodyRowCount = 1;
    String[] cellValues = {"序号", "线缆温度", "电流", "电压", "电池电流", "震动", "433节点数据", "信号强度", "板子温度", "数据时间"};
    List sheetNameList = lineInfoList.stream().map(item-> item.getName()+"_"+item.getId()
    ).collect(Collectors.toList());

    Map>> dataMap = new HashMap<>();
    for (Line line : lineInfoList) {
        //正文内容
        List> valueList = new ArrayList<>();
        List dateList = lineDateMap.get(line.getId());
        for (DataLineHistoryVO item : dateList) {
            List list = new ArrayList<>();
            list.add(String.valueOf(bodyRowCount++));
            list.add(item.getLineTemp());
            list.add(item.getLineA());
            list.add(item.getLineV());
            list.add(item.getBatteryA());
            list.add(item.getShake());
            list.add(item.getNode433());
            list.add(item.getSignal());
            list.add(item.getCBTemp());
            list.add(df.format(item.getCreateTime()));
            valueList.add(list);
        }
        bodyRowCount = 1;
        dataMap.put(line.getName()+"_"+line.getId(),valueList);
    }
    return new BaseDataRespDTO(ReturnCodeConstant.SUCCESS,ExcelSheetsUtil.dataToExcel(sheetNameList,dataMap,cellValues));
}

Java导出多个Sheet的Excel,并上传到Ftp_第1张图片
Java导出多个Sheet的Excel,并上传到Ftp_第2张图片

你可能感兴趣的:(备忘,多个sheet,导出execl,上传Ftp)