我正在尝试通过 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
和 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");
如果您不想创建一个临时的 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");
关于java - 通过带有 excel 文件的 java 应用程序发送电子邮件 - 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16851199/