【问题标题】:How to export an image that is a blob in database from a jasper reports to excel?如何将数据库中的 blob 图像从碧玉报告导出到 excel?
【发布时间】:2015-11-24 12:47:38
【问题描述】:

在 ireportDesigner 5.6.0 中,我正在从数据库中添加图像。当我添加该图像时,它在 xml 中显示为java.lang.Object,我已将其更改为java.awt.Image,如下图所示

我已将表达式类一次更改为“java.awt.Image”,另一次更改为“java.io.InputStream”。现在,当我点击“预览”选项卡时,图像即将到来并且是完美的。

现在问题出现了。

当我将 jrxml 和 jasper 文件集成到 eclipse 并运行服务器时,它显示类似“无法添加单元格。

这是我的代码:

report1.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report1" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="d9b53979-ad44-4ad1-aedf-164f742a3c02">
    <queryString>
        <![CDATA[select company_profile.companyLogo,
company_profile.companyLetterHead
from
company_profile]]>
    </queryString>
    <field name="companyLogo" class="java.lang.Object">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <field name="companyLetterHead" class="java.lang.Object">
        <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    <title>
        <band height="79" splitType="Stretch">
            <image>
                <reportElement x="0" y="0" width="107" height="79" uuid="fba6c6a9-42a2-4ffb-9d80-f0721728a7b6"/>
                <imageExpression><![CDATA[$F{companyLogo}]]></imageExpression>
            </image>
            <image>
                <reportElement x="107" y="0" width="448" height="79" uuid="b0e3a3f8-424b-4780-926f-95d15f8e0cc5"/>
                <imageExpression><![CDATA[$F{companyLetterHead}]]></imageExpression>
            </image>
        </band>
    </title>
</jasperReport>

addCompanyProfile.jsp

<script language="javascript">
            function Checkfiles()
            {
                var fup = document.getElementById('filename');
                var fileName = fup.value;
                var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
                if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc")
                {
                    return true;
                } 
                else
                {
                    alert("Upload an image");
                    fup.focus();
                    return false;
                }
            }
        </script>
    <body>
                        <td></td><br>
                        <td><html:submit value="Update"
                                style="width:70px;height:25px;" /></td>
                        </table>

                        </html:form>
                        <br/>
                       <%-- Photo edit --%>
                    <FORM ENCTYPE="multipart/form-data" ACTION="uploadCompanyLogo.jsp" METHOD=POST onsubmit="return Checkfiles();">
                        <table border="0">

                            <tr>
                                <td style="padding-left:100px;" colspan="2" align="center"><B>UPLOAD LOGO AND LETTER HEAD HERE:-</B><center></td>
                                </tr>

                                <tr>
                                    <td style="padding-left:100px;"><b>Add Logo:</b></td>
                                    <td><INPUT NAME="file" TYPE="file" id="filename" size="7"></td>
                                     <td colspan="2" align="center"><input type="submit" value="Upload Logo"> </td>
                                </tr>
                               </table>        
                    </FORM>

                    <FORM ENCTYPE="multipart/form-data" ACTION="uploadLetterHead.jsp" METHOD=POST onsubmit="return Checkfiles1();">
                        <table border="0"> 
                                <tr>
                                 <td style="padding-left:100px;"><b>Add LetterHead:</b></td>
                                    <td><INPUT NAME="file" TYPE="file" id="filename" size="7"></td>
                                    <td style="padding-left:50px;" colspan="2" align="center"><input type="submit" value="Upload LetterHead"> </td>

                                </tr>

                       </table> 
                       </FORM>
            </div>
             <div>


                    <%-- for further help <a href="/SalesPropeller/Profile/helpImg.jsp">Click Here</a> --%>
                </div>
</body>

uploadCompanyLogo.jsp

<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.zip.*"%>
<%
    String email = (String) session.getAttribute("email");
    String saveFile = "";
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
        }
        String file = new String(dataBytes);
        saveFile = file.substring(file.indexOf("filename=\"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1, contentType.length());
        int pos;
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
        File ff = new File(saveFile);
        FileOutputStream fileOut = new FileOutputStream(ff);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();
%><Br><table border="2"><tr><td><b>You have successfully upload the file:</b>
            <%out.println(saveFile);%></td></tr></table>
<%
        Connection connection = null;
        ResultSet rs = null;
        PreparedStatement psmnt = null;
        FileInputStream fis;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database", "root", "root");
            File f = new File(saveFile);
            psmnt = connection.prepareStatement("UPDATE marketing_database.company_profile SET `companyLogo`=? WHERE `id`='1';");
            fis = new FileInputStream(f);
            psmnt.setBinaryStream(1, (InputStream) fis, (int) (f.length()));
            int s = psmnt.executeUpdate();
            if (s > 0) {
                System.out.println("Uploaded successfully !");
            } else {
                System.out.println("Error!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
%>

<%
response.sendRedirect("/SalesPropeller/Admin/Profile/addCompanyProfile.jsp");
%>

QuotationXLS.jsp

<body>

<%
String sql=null;
Connection conn = null;
try 
{
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database","root","root");
    sql = "select company_profile.companyLogo,company_profile.companyLetterHead,company_profile.companyName AS 'cname',quotationclient_details.RefNo,quotationclient_details.Date,quotationclient_details.CustomerName,quotationclient_details.CompanyName,quotationclient_details.PaymentTerm,quotationclient_details.DeliveryTime,quotationclient_details.Validity,quotation.Item,quotation.id,quotation.Description,quotation.Quantity,quotation.PerUnitPrice,quotation.TotalPrice,quotation.VAT5,quotation.VAT14,quotation.CST,quotationclient_details.MobileNo,quotation.ServiceTax from quotation,quotationclient_details,company_profile where quotation.CId In (select max(CId) from quotationclient_details) and quotationclient_details.CId In (select max(CId) from quotationclient_details)";
    ServletContext context = request.getServletContext(); 
    String fullPath = context.getRealPath("/WEB-INF/reports/report9.jrxml");
    InputStream input = new FileInputStream(new File(fullPath));
    JasperDesign jasperDesign = JRXmlLoader.load(input);

    System.out.println("Compiling Report Designs");
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    System.out.println("Creating JasperPrint Object");
    HashMap<String,Object> map = new HashMap<String,Object>();
    map.put("sql",sql);
    JasperPrint jasperPrint = JasperFillManager.fillReport (jasperReport,map,conn); 
    byte bytes[] = new byte[10000]; 

    JRXlsExporter exporter = new JRXlsExporter(); 
    ByteArrayOutputStream xlsReport = new ByteArrayOutputStream(); 
    exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE); 
    exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS,Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS,Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.TRUE);
    exporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, xlsReport); 
    exporter.exportReport(); 
    String fileName = "QuotationReport.xls";
response.setHeader("Content-Disposition", "inline; filename="
+ fileName);
    response.setContentType("application/vnd.ms-excel"); 
    response.setContentLength(xlsReport.size()); 

    OutputStream outputStream = response.getOutputStream(); 
    System.out.println("After JasperPrint = 4"); 
    xlsReport.writeTo(outputStream); 
    outputStream.flush(); 
    } 
    catch(Exception e) 
    {e.printStackTrace();} 

        %>
</body>
</html>

【问题讨论】:

  • company_profile.companyLogo 是图像路径的字符串,还是某种奇怪的 blob?
  • @PetterFriberg 这是一个长斑点
  • @PetterFriberg 在导出到 XLS 时,它没有导出并显示类似“无法添加单元格”的错误。在 PDF 和 DOC 中它正在导出,因为我在 XML 中将“java.lang.Object”更改为“java.awt.Image”,并且将包含“java.lang.String”的“Expression Class”更改为“java.awt.Image” "。
  • @PetterFriberg 我编辑并添加了 3 个 jsp 1)addCompanyProfile.jsp 2)uploadCompanyLogo.jsp 3)uploadCompanyLetterHead.jsp
  • @PetterFriberg 添加您所说的内容后,显示错误,如图所示。

标签: jasper-reports blob export-to-excel


【解决方案1】:

有了您添加的其他信息,我会这样做:

  1. 正确的字段类应该是java.sql.Blob(对应数据库映射)

    <field name="companyLogo" class="java.sql.Blob">
       <fieldDescription><![CDATA[]]></fieldDescription>
    </field>
    
  2. 图像表达式应该是(在Blob 上,我们称getBinaryStream() 为我们提供java.io.InputStream

     <image>
        <reportElement x="0" y="0" width="107" height="79" uuid="fba6c6a9-42a2-4ffb-9d80-f0721728a7b6"/>
        <imageExpression class="java.io.InputStream"><![CDATA[$F{companyLogo}.getBinaryStream()]]></imageExpression>
     </image>
    

为了改进代码,最好检查一下$F{companyLogo}!=null

一个小提示...为什么不将它作为参数传递,因此将其加载到您的 java 中并将其作为 java.io.InputStream 或 java.io.Image 传递...这样也许您的 jasper 也会变得更干净。 ..

【讨论】:

  • @AlbertoAcuña 在 printWhenExpression 因此避免在没有徽标的情况下打印元素,生成空指针异常
  • 如果我们将 glob 作为参数传递,请您解释一下步骤。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多