Como fazer isso ?
@Override
public void exportar() {
try {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("razao");
XSSFRow row = sheet.createRow(0);
XSSFCell cell;
cell = row.createCell(0);
cell.setCellValue("sku");
cell = row.createCell(1);
cell.setCellValue("nome");
cell = row.createCell(2);
cell.setCellValue("marketPlaceProduto");
Integer contador = 1;
Produto produto = repository.findById("00051d6b-2003-432c-be1d-e057e1a8b415").get();
// for (Produto produto : produtos) {
row = sheet.createRow(contador);
cell = row.createCell(0);
cell.setCellValue(produto.getSku());
cell = row.createCell(1);
cell.setCellValue(produto.getNome());
cell = row.createCell(2);
cell.setCellValue(produto.getMarketPlaceProduto().getDescricao());
contador++;
// }
File fileTemprario = File.createTempFile("xlsx", "xlsx");
fileTemprario.setReadOnly();
log.info("File path: " + fileTemprario.getAbsolutePath());
fileTemprario.deleteOnExit();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
Ele esta gerando corretamente o excel, quando coloco este código no final
FileOutputStream out = null;
try {
out = new FileOutputStream(new File("C:\\teste\\arquivo.xlsx"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
workbook.write(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Só que vou fazer isso via thread e após o termino, preciso pegar o excel gerado pelo XSSFWorkbook e enviar por email, salvar em disco ou salvar no bd
Como fazer ?
@guilhermebhte Olá,
Pra ti enviar por e-mail com anexo e usando password, segue o exemplo:
//pode testar com host do outlook : smtp-mail.outlook.com
String host = "smtp.gmail.com", user = "email para autenticacao", password = "senha do email";
int port = 25;
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);//se for testar local tem que abrir essa porta no firewall
props.put("mail.debug", "true");
props.put("mail.smtp.password", password);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
//props.put("mail.smtp.EnableSSL.enable", "true"); caso o servidor de email queira o protocolo de criptografia SSL descomente esse e comente o de cima que TTL
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};
Session session = Session.getInstance(props, auth);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("email de envio"));
message.setRecipient(RecipientType.TO, new InternetAddress("email de destino"));
message.setSubject("E-mail com anexo");
message.setText("arquivo pdf anexado!", "UTF-8"); // as "text/plain"
message.setSentDate(new Date(System.currentTimeMillis()));
//anexando arquivo --------------------
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "F:\\CAMINHO_DO_ARQUIVO\\VS-vs-SO.pdf";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart2);
message.setContent(multipart);
//--------------------------
Transport transport = session.getTransport("smtp");
transport.connect(host, port, user, password);
transport.send(message);
transport.close();
System.out.println("e-mail enviado com sucesso");
se estiver usando o maven use essa dependencia para enviar o email
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
1 curtida
Aqui vc pos fixo. Mas o arquivo tem que ser gravado temporário. Como faço isso ?
Para ser temporário vc deve enviar e depois excluir o arquivo, pesquise sobre como remover um arquivo
1 curtida
O seu exemplo, entendo que é maquina windows. mas se for maquina linux ?
Vi que tem isso abaixo, mas não consegui progredir
File fileTemprario = File.createTempFile(“xlsx”, “xlsx”);,
e para deletar
fileTemprario.deleteOnExit();
Cara eu vi esse exemplo aqui
String prefix = "exampleTempFile";
String suffix = ".txt";
//Creating a temp file
Path tempFilePath = Files.createTempFile(prefix, suffix);
//o caminho ta aqui ele independe de OS
System.out.println("Temp file created: "+tempFilePath.toString());
//Deleting the file
Files.deleteIfExists(tempFilePath);
Dai vc pega o path e faz o que quiser pra deleta esta ai tambem vc coloca depois de enviado o arquivo por email