poi 生成Excel 并发送到ftp服务器(不生成本地文件)

jar包

  <dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
      <artifactId>org.apache.poi.xwpf.converter.core</artifactId>
      <version>1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>

public void poiAndFtp () {



// 创建一个excel文件
HSSFWorkbook book = new HSSFWorkbook();
// 创建Sheet对象
HSSFSheet sheet = book.createSheet("机构客户信息表");


// 创建excel文件标题
String[] tableHeader = { "客户编号", "分支代码", "经办人"};


HSSFRow row = null;
HSSFCell cell = null;
int rowIndex = 2;
row = sheet.createRow(1);
int i = 0;
for (String string : tableHeader) {
cell = row.createCell(i);
cell.setCellValue(string);
i++;
}


for (VenusOrgan organ : list) {
row = sheet.createRow(rowIndex);
cell = row.createCell(0);
cell.setCellValue(organ.getOrgan_id());

cell = row.createCell(1);
cell.setCellValue(organ.getBranch_no());

cell = row.createCell(2);
cell.setCellValue(organ.getOperator_no());

cell = row.createCell(3);
cell.setCellValue(organ.getOrgan_name());

rowIndex++;
}


FTPClient ftp = new FTPClient();


try {
// 连接ftp服务器
ftp.connect("192.168.1.36", 21);
// 登录
ftp.login("BILG201711016", "1016");
// 设置上传路径
String path = "/poi";
// 检查上传路径是否存在 如果不存在返回false
boolean flag = ftp.changeWorkingDirectory(path);
System.out.println(flag);
if (!flag) {
// 创建上传的路径 该方法只能创建一级目录,在这里如果/home/ftpuser存在则可创建image
ftp.makeDirectory(path);
System.out.println("11");
}
// 指定上传路径
ftp.changeWorkingDirectory(path);
// 指定上传文件的类型 二进制文件
ftp.setFileType(FTP.BINARY_FILE_TYPE);



ByteArrayOutputStream os = new ByteArrayOutputStream();
book.write(os);
byte[] b = os.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(b);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy_MM_dd");
Date date = new Date();
String name = new String(("机构客户信息表_"+sdf.format(date)+".xls").getBytes("GBK"), "iso-8859-1");//涉及到中文问题 根据系统实际编码改变 

System.out.println("机构客户信息表_"+sdf.format(date)+".xls");
ftp.storeFile(name, in);
} catch (Exception e) {
e.printStackTrace();
}


}

猜你喜欢

转载自my.oschina.net/hfq/blog/1817769