我试图通过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);
您需要将选项卡限制数据输出到 Excel 文件中。仅调整 MIME 类型不会使 Excel 认为您的选项卡受到限制text文件为 Excel 文档。
任何电子表格文件都具有完全不同的二进制结构。它需要有一个Workbook
, Worksheets
and Rows
of Cell
内的数据;并且它们显然从您的文本文件中丢失了。这就是为什么它没有按照您期望的方式工作。
这是您可以使用的方法阿帕奇兴趣点 http://poi.apache.org/创建一个临时 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");
如果您不想创建临时 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");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)