我试图通过Java应用程序发送邮件,其中excel文件作为附件而不实际创建文件.excel文件中的数据来自数据库.我能够发送带附件的邮件,但文件是文本(制表符分隔)格式.但我希望文件只能是Excel格式.
请帮忙....
以下是代码:
//Here goes my DBConnection and Query code
while(rs.next())
{
for(int i=1;i<13;i++)
{
//tab for each column
exceldata = exceldata+""+"\t";
}
// new line for end of eachrow
exceldata = exceldata+"\n";
}
String data = exceldata;
String filename="example";
MimeMessage msg = new MimeMessage(session);
//TO,From and all the mail details goes here
DataSource fds = new ByteArrayDataSource(data,"application/vnd.ms-excel");
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText("Hi");
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(filename);
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
msg.setContent(mp);
msg.saveChanges();
// Set the Date: header
msg.setSentDate(new java.util.Date());
Transport.send(msg);
Run Code Online (Sandbox Code Playgroud)
Rav*_*yal 20
您需要将标签限制数据输出到Excel文件中.只是调整MIME类型不会使Excel将标签限制文本文件视为Excel文档.
任何电子表格文件都具有不同的二进制结构.它需要有一个Workbook,Worksheets和Rows的Cell内部数据; 它们在您的文本文件中明显丢失.这就是为什么它不按你期望的方式工作的原因.
以下是如何使用Apache POI创建临时excel文件以便稍后用作邮件附件.
Workbook xlsFile = new HSSFWorkbook(); // create a workbook
CreationHelper helper = xlsFile.getCreationHelper();
Sheet sheet1 = xlsFile.createSheet("Sheet #1"); // add a sheet to your workbook
while(rs.next())
{
Row row = sheet1.createRow((short)0); // create a new row in your sheet
for(int i = 0; i < 12; i++)
{
row.createCell(i).setCellValue(
helper.createRichTextString(exceldata)); // add cells to the row
}
}
// Write the output to a temporary excel file
FileOutputStream fos = new FileOutputStream("temp.xls");
xlsFile.write(fos);
fos.close();
// Switch to using a `FileDataSource` (instead of ByteArrayDataSource)
DataSource fds = new FileDataSource("temp.xls");
Run Code Online (Sandbox Code Playgroud)
如果你不想创建一个临时的excel文件来转储数据,这里的数据是如何实现的
ByteArrayOutputStream bos = new ByteArrayOutputStream();
xlsFile.write(bos); // write excel data to a byte array
fos.close();
// Now use your ByteArrayDataSource as
DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/vnd.ms-excel");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28747 次 |
| 最近记录: |