user3678624
user3678624

Reputation: 75

I have my own code to create a excel file and I want to send that as an attachment to email without saving file in local system

I am working on a case where I will be supplied with data and I will create a excel file using that data.

Right now I am creating it in my local system and later adding that as an attachment and sending through email using Java Mail Service.

But I dont want to store excel file in my local system and I want to just pass the stream object to email service and send email. So that there wont be any local storage of file still able to send attachment.

Please reply if there is any solution ?

// Created WorkBook HSSFWorkbook workbook = new HSSFWorkbook();

FileOutputStream outputStream = new FileOutputStream(FILE_NAME)) workbook.write(outputStream);

here FILE_NAME is fully qualified system path where I will be storing file.

I want to skip this and directly send attachment

Upvotes: 0

Views: 2301

Answers (3)

user12792991
user12792991

Reputation:

Workbook workbook=new XSSFWorkbook();
Sheet sheet =workbook.createSheet(" ");
Font HearderFont=workbook.createFont();
HearderFont.setBold(true);
HearderFont.setFontHeightInPoints((short)9);
HearderFont.setColor(IndexedColors.RED.getIndex());
CellStyle hearderCellStyle=workbook.createCellStyle();
hearderCellStyle.setFont(HearderFont);
//excel file maker
int rownum=1;
for(MailModelClass mailModelonbj:dataStored) {
  Row row=sheet.createRow(rownum++);
  row.createCell(0).setCellValue(mailModelonbj.(any));
  row.createCell(1).setCellValue(mailModelonbj.(any));
  row.createCell(2).setCellValue(mailModelonbj.(any));
}

Upvotes: 0

Bill Shannon
Bill Shannon

Reputation: 29971

Write the data to a ByteArrayOutputStream, get the bytes, and use a ByteArrayDataSource to supply the data to JavaMail:

mbp.setDataHandler(new DataHandler(
    new ByteArrayDataSource(bytes,
       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")));

Upvotes: 0

cisk
cisk

Reputation: 618

I'm using an approach like this and it is working fine:

File file = File.createTempFile("Report", "xlsx");
file.deleteOnExit();
Path path = file.toPath();
try (final FileOutputStream fileOut = new FileOutputStream(file)) {
    try (final XSSFWorkbook workbook = new XSSFWorkbook()) {
        //create your sheets here

        workbook.write(fileOut);
        return Files.readAllBytes(path);
    } catch (Exception e) {
        LOG.error("Error during creation of excel report", e);
        throw e;
    } finally {
        if (path != null) {
            try {
                Files.delete(path);
            } catch (final IOException e) {
                LOG.error("Unable to delete file:" + path.toString(), e);
            }
        }
    }
}

Upvotes: 0

Related Questions