1. 程式人生 > 實用技巧 >java 自動生成xsl excel 不生成本地檔案,通過流的方式上傳ftp

java 自動生成xsl excel 不生成本地檔案,通過流的方式上傳ftp


import com.bit.bpc.extend.report.client.api.MsaApiFeignClient;
import com.bit.bpc.extend.report.client.api.model.GroupUserVO;
import com.bit.bpc.extend.report.emos.model.fault.EmosFaultProcessInfo;
import com.bit.bpc.extend.report.emos.repository.fault.EmosFaultProcessInfoMapper;
import com.bit.bpc.extend.report.emos.service.fault.dwftp.FTPTools;
import com.bit.bpc.extend.report.utils.DateUtils;
import com.bit.bpc.extend.report.utils.FeignResultUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.supercsv.io.CsvListWriter;
import org.supercsv.io.ICsvListWriter;
import org.supercsv.prefs.CsvPreference;

import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
* @author ljk
* @version 1.0
* @date 2020/11/11 11:06
*/
@Component
public class FTPUtils {

private static final Logger log = LoggerFactory.getLogger(FTPTools.class);

@Autowired
MsaApiFeignClient msaApiFeignClient ;
@Autowired
private EmosFaultProcessInfoMapper processInfoMapper;

/**
* 每天凌晨1點執行定時任務推送上一天的資料
*/
//@Scheduled(cron="*/15 * * * * ?") //每15秒 執行一次
//@Scheduled(cron="0 0 1 * * ?") //每天凌晨1點執行一次
public void planFaultOrderNum() {
log.info(DateUtils.getDataFormat(new Date())+" >>>>>>>planFaultOrderNum()執行....");
//生成檔案 並上傳ftp
try {
sendExcelsFtp();
} catch (IOException e) {
e.printStackTrace();
}
}


public void sendExcelsFtp() throws IOException {

Properties pro = System.getProperties();
System.out.println("當前編碼格式:"+pro.getProperty("file.encoding"));

//列頭
String[] headers = {"人員手機號","人員唯一標識","姓名","地市","區縣","時間","專業","處理故障數"};

HSSFWorkbook wb = new HSSFWorkbook();
// 生成一個表格
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(headers[i]);
}
//List<GroupUserVO> groupUsers = FeignResultUtils.msaResult(msaApiFeignClient.getGroupUsersByGroupId(group.getGroup_id()));
List<EmosFaultProcessInfo> listmaps = processInfoMapper.getdaiweiOrder();
log.info("listmaps.size : "+listmaps.size());

EmosFaultProcessInfo processInfo=null;
//寫入資料
for (int j=0;j<listmaps.size(); j++){
row = sheet.createRow(j+1);
processInfo = listmaps.get(j);
List<GroupUserVO> groupUsers = FeignResultUtils.msaResult(msaApiFeignClient.getGroupUsersByGroupId(processInfo.getDaiweiGroupId()));
GroupUserVO groupUserVO = groupUsers.get(1);

row.createCell(0).setCellValue(groupUserVO.getMobile());
row.createCell(1).setCellValue(groupUserVO.getUserAccount());
row.createCell(2).setCellValue(groupUserVO.getUserName());
row.createCell(3).setCellValue(processInfo.getRegion());
row.createCell(4).setCellValue(processInfo.getCountry());
row.createCell(5).setCellValue(processInfo.getProcessCreateTime());
row.createCell(6).setCellValue(processInfo.getNetClassOne());
row.createCell(7).setCellValue(processInfo.getId()); //總數

}

for (int i = 0; i < headers.length; i++) {
sheet.autoSizeColumn(i);
}

ByteArrayOutputStream os=null;
ByteArrayInputStream iss=null;
try {
os = new ByteArrayOutputStream(1000);
wb.write(os);
iss = new ByteArrayInputStream(os.toByteArray());
String cvsName="01001_"+DateUtils.getCurrentDateDate()+".xls"; //檔名 xls
log.info("檔名01001_cvsName---------"+cvsName);

// 開始上傳檔案
String hostname=""; //ip地址
int port=21;
String username="inspurftp";
String password="inspurftp#238";
String ftpPath="/eoms_data"; //路徑
//String ftpPath="/"; //路徑

/* String hostname="192.168.10.58"; //ip地址
int port=21;
String username="lj-ftp";
String password="admin123";
String ftpPath="/localuser/newfilecsv"; //路徑*/

uploadFile(hostname, port, username, password, "/", ftpPath, cvsName, iss);

os.flush();
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
wb.close();
os.close();
iss.close();
}
}


/**
* Description: 向FTP伺服器上傳檔案
* @param host FTP伺服器hostname
* @param port FTP伺服器埠
* @param username FTP登入賬號
* @param password FTP登入密碼
* @param basePath FTP伺服器基礎目錄
* @param filePath FTP伺服器檔案存放路徑。例如分日期存放:/2020/01/01。檔案的路徑為basePath+filePath
* @param filename 上傳到FTP伺服器上的檔名
* @param input 輸入流
* @return 成功返回true,否則返回false
*/
public boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);// 連線FTP伺服器
// 如果採用預設埠,可以使用ftp.connect(host)的方式直接連線FTP伺服器
ftp.login(username, password);// 登入
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
//切換到上傳目錄
/* if (!ftp.changeWorkingDirectory(basePath+filePath)) {
//如果目錄不存在建立目錄
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}*/

//目錄存在
if (ftp.changeWorkingDirectory(filePath)) {

//設定上傳檔案的型別為二進位制型別
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上傳檔案
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
}

} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}



}