将Excel文件(在内存中)作为附件发送到Google App Engine上

时间:2011-10-05 02:01:49

标签: java google-app-engine javamail jexcelapi

我用谷歌搜索并尝试了几种方法但失败了。 这是一个问题:我尝试创建一个excel文件(使用JExcelApi)并将其作为附件发送到谷歌应用引擎上。

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {
        //write the excel file
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
        //first sheet
        WritableSheet sheet = workbook.createSheet("Param", 0);
        Label label11 = new Label(0, 0, "parameter is"); 
        sheet.addCell(label11);
        Label label12 = new Label(1, 0, "worker"); 
        sheet.addCell(label12);

        //second sheet
        WritableSheet sheet2 = workbook.createSheet("Info", 1);
        Label label21 = new Label(0, 0, "Info is"); 
        sheet2.addCell(label21);
        Label label22 = new Label(1, 0, "consumer"); 
        sheet2.addCell(label22);

        workbook.write(); 
        workbook.close();

        //email the excel file as an attachment
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("//my gmail", "Sr."));
        msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress("//my gmail", "Mr. "));
        msg.setSubject("Your excel file is here");

        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();        
        htmlPart.setContent("please review", "text/html");
        mp.addBodyPart(htmlPart);

        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setFileName("report.xls");
        attachment.setContent(outputStream.toByteArray(), "application/vnd.ms-excel");              
        mp.addBodyPart(attachment);

        msg.setContent(mp);
        Transport.send(msg);

    } catch (RowsExceededException e) {
        /* foo */
    }
}

我上传但从未将附带excel的邮件发送到我的邮箱。 outputStream.toByteArray()可能不合适,但我尝试的其他人也没有用。

1 个答案:

答案 0 :(得分:1)

解决它。但是有人可以解释一下吗?因为谷歌app引擎的一些限制?谢谢。

DataSource src = new ByteArrayDataSource(outputStream.toByteArray()
                                       , "application/vnd.ms-excel");

attachment.setDataHandler(new DataHandler(src));