JAVA -- 生成Excel 并上传到 FTP 不生成本地文件

27 篇文章 0 订阅
23 篇文章 1 订阅

直接上代码

POM.XML 这里只是主要的jar

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.17</version>
</dependency>
/**
     * 导出excel
     * @param fileName 要导出的文件名(包含路径)
     * @param data
     * @return
     */
    public boolean exportToExcel(String fileName, List<String[]> data)  {

        log.info("导出excel开始,fileName: " + fileName + ", data个数:" + data.size());
        if (!fileName.endsWith(".xlsx")){
            log.error("fileName有误,需要以xlsx结尾");
            return false;
        }
        // 声明一个工作薄
        Workbook workBook = null;
        boolean result = false;
        ByteArrayOutputStream ops = null;
        ByteArrayInputStream in = null;
        File file = new File(fileName);
        try {
            if (file.exists()) {
                file.delete();
            }
            file = new File(fileName);
            //重新复制模版文件
            FileUtils.copyFile(new File(ExcelExportUtil.class.getResource("/template/policy_Template.xlsx").getFile()),file);
            // 声明一个工作薄
            workBook = new XSSFWorkbook(new FileInputStream(file));
            // 生成一个表格
            Sheet sheet = workBook.getSheetAt(0);
            if (sheet == null) {
                sheet = workBook.createSheet("AutoPolicy");
            }
            //最新Excel列索引,从0开始
            int lastRowIndex = sheet.getLastRowNum();
            lastRowIndex++;
            // 设置表格默认列宽度
            sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
            // 产生表格表头列标题行
            Row row ;
            NumberFormat decimalFormat = new DecimalFormat("###,###.00");
            DecimalFormat zeroFormat = new DecimalFormat("0.00");
            // 遍历集合数据,产生数据行,前两行为标题行与表头行
            for (String[] dataRow : data) {
                row = sheet.createRow(lastRowIndex);
                lastRowIndex++;
                for (int j = 0; j < dataRow.length; j++) {
                    Cell contentCell = row.createCell(j);
                    String dataObject = dataRow[j];
                    if (dataObject != null) {
                        if (isNumeric(dataObject)){
                            contentCell.setCellType(CellType.NUMERIC);
                            if (dataObject.contains(".")){
                                if(new BigDecimal(dataObject).compareTo(BigDecimal.ZERO) == 0){
                                    contentCell.setCellValue(zeroFormat.format(0));
                                }else {
                                    contentCell.setCellValue(decimalFormat.format(new BigDecimal(dataObject)));
                                }
                            }else {
                                contentCell.setCellValue(dataObject);
                            }
                        } else {
                            contentCell.setCellType(CellType.STRING);
                            contentCell.setCellValue(dataObject);
                        }
                    } else {
                        // 设置单元格内容为字符型
                        contentCell.setCellValue("");
                    }
                }
            }
            ops = new ByteArrayOutputStream();
            workBook.write(ops);
            byte[] b = ops.toByteArray();
            in = new ByteArrayInputStream(b);
            fileStreamUpload.uploadFile(in, fileName);
            result = true;
            ops.flush();
            file.delete();
            System.out.println("success");
        } catch (Exception e) {
            log.error("导出excel失败,失败原因:" + e.getMessage());
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(workBook);
            IOUtils.closeQuietly(ops);
            IOUtils.closeQuietly(in);
        }
        return result;
    }

其中:

注意点: 1、fileName 为文件名(.xlsx)。 

                2、只需要生成本地文件,只需要修改如下:

ops = new FileOutputStream(file);
workBook.write(ops);
ops.flush();
result = true;

               3、policy_Template.xlsx 为模板文件(放着我们生成的excel文件的Title)

               4、NumberFormat decimalFormat = new DecimalFormat("###,###.00"); 格式化金额

               5、FTP 上传代码:

public void uploadFile(InputStream inputStream,String fileName) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		try {
			while ((len = inputStream.read(buffer)) > -1) {
				baos.write(buffer, 0, len);
			}
			baos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
		InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());
		BufferedInputStream inBuf = null;
		String ftpPath = CommUtil.fetchSystemDate("yyyy-MM-dd") + "/export_policy/";
		// 数据库存入地址
		try {
			inBuf = new BufferedInputStream(stream1);
			// 开始上传文件
			FileFtp ftp = new FileFtp();
			ftp.login(ftpIp, ftpUser, ftpPassWord);
			ftp.CreateDirecroty(ftpPath);
			ftp.uploadFile(inBuf, fileName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (stream1 != null)
					stream1.close();
				if (stream2 != null)
					stream2.close();
				if (stream2 != null)
					inputStream.close();
				if (inBuf != null)
					inBuf.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

如有疑问,评论或加QQ+41717972@qq.com

补充FileFtp代码:
 


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileFtp {
    FileFtp instance;
	private FTPClient ftpClient = null;
	
	public synchronized FileFtp getInstance() {
		if (instance == null) {
			instance = new FileFtp();
		}
		return instance;
	}
	
	public void login(String s_url, String uname, String pass) {
		ftpClient = new FTPClient();
		try {
			// 连接
			ftpClient.connect(s_url);
			ftpClient.login(uname, pass);
			// 检测连接是否成功
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				this.closeCon();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			// 关闭
			this.closeCon();
		}
	}
	
	public boolean uploadFile(InputStream in, String targetFname) {
		boolean flag = false;
		if (ftpClient != null) {
			BufferedInputStream buff = new BufferedInputStream(in);
			try {
				// 设置上传目录
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				// 设置文件类型(二进制)
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				// 重新开放新端口
				ftpClient.enterLocalPassiveMode();
				// 上传
				flag = ftpClient.storeFile(targetFname, buff);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if(buff != null)
					buff.close();
					if(in != null)
					in.close();
					this.closeCon();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return flag;
	}
	
	public void closeCon() {
		if (ftpClient != null) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.logout();
					ftpClient.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			ftpClient = null;
		}
	}
	
	
    public boolean removeFile(String srcFname){  
        boolean flag = false;  
        if( ftpClient!=null ){  
            try {  
                flag = ftpClient.deleteFile(srcFname);  
            } catch (IOException e) {  
                e.printStackTrace();
            }finally{
            	 this.closeCon();  
            }
        }  
        return flag;  
    }
	
	public boolean CreateDirecroty(String remote) throws IOException {
		boolean success = true;
		String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
		// 设置初始地址
		ftpClient.changeWorkingDirectory("/");
		// 如果远程目录不存在,则递归创建远程服务器目录
		if (!directory.equalsIgnoreCase("/") && !ftpClient.changeWorkingDirectory(new String(directory))) {
			int start = 0;
			int end = 0;
			if (directory.startsWith("/")) {
				start = 1;
			} else {
				start = 0;
			}
			end = directory.indexOf("/", start);
			while (true) {
				String subDirectory = new String(remote.substring(start, end));
				if (!ftpClient.changeWorkingDirectory(subDirectory)) {
					if (ftpClient.makeDirectory(subDirectory)) {
						ftpClient.changeWorkingDirectory(subDirectory);
					} else {
						success = false;
					}
				}
				start = end + 1;
				end = directory.indexOf("/", start);
				// 检查所有目录是否创建完毕
				if (end <= start) {
					break;
				}
			}
		}
		return success;
	}
}

  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
您可以使用以下代码来生成CSV文件上传FTP服务器: ```java import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; public class CSVGenerator { public static void main(String[] args) { generateCSV(); } public static void generateCSV() { String csvFilePath = "path/to/csv/file.csv"; String ftpServer = "ftp.example.com"; int ftpPort = 21; String ftpUser = "username"; String ftpPassword = "password"; String ftpDirectory = "/path/to/ftp/directory/"; try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(csvFilePath), StandardCharsets.UTF_8))) { // 写入CSV文件内容 writer.write("列1,列2,列3\n"); writer.write("数据1,数据2,数据3\n"); writer.write("数据4,数据5,数据6\n"); // 添加更多数据行... // 上传CSV文件FTP服务器 FTPClient ftpClient = new FTPClient(); ftpClient.connect(ftpServer, ftpPort); ftpClient.login(ftpUser, ftpPassword); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(ftpDirectory); ftpClient.storeFile("file.csv", new FileInputStream(csvFilePath)); ftpClient.logout(); ftpClient.disconnect(); System.out.println("CSV文件生成并成功上传FTP服务器!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 请注意,您需要先在项目中添加 Apache Commons Net 库的依赖,以便使用 `FTPClient` 类。您可以在 Maven 中添加以下依赖项: ```xml <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.7.2</version> </dependency> ``` 请将以下变量替换为您自己的值: - `csvFilePath`:CSV文件的本地路径和文件名。 - `ftpServer`:FTP服务器的地址。 - `ftpPort`:FTP服务器的端口号(默认为21)。 - `ftpUser`:FTP服务器的用户名。 - `ftpPassword`:FTP服务器的密码。 - `ftpDirectory`:要上传到的FTP服务器的目录路径。 这段代码会生成一个包含示例数据的CSV文件,并将其上传到指定的FTP服务器。您可以根据自己的需求修改CSV文件的内容和上传的逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小帅和刘美美

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值