1. 程式人生 > >JAVA -- 生成Excel 並上傳到 FTP 不生成本地檔案

JAVA -- 生成Excel 並上傳到 FTP 不生成本地檔案

直接上程式碼

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();
			}
		}
	}

如有疑問,評論或加[email protected]