If statement in TextField [duplicate] - jasper-reports

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I want to display different column header text and regarding this header different values as well in my table. The header text and the value depends on one Parameter value. This parameter is defined in the "Parameters" section of the report as String, I also see it on the "Preview" view and I also give it a value there.
My problem is, that it's not working (this column is always empty: no header text, no value in detail) :) How can I use properly any IF statement here? This is my code for the table header:
($P{first_column} == "first_column") ? "First Column" : ($P{first_column} == "second_column" ? "Second Column" : ($P{first_column} == "third_column" ? "Third Column" : ""))
What am I doing wrong? Thank you!
EDIT.:
this is the TextField expresion copied from the "source" view:
<textField>
<reportElement mode="Opaque" x="0" y="0" width="58" height="30" backcolor="#CFCFCF" uuid="96edf250-4a1c-4448-8995-3753c76f4a1e"/>
<textElement verticalAlignment="Middle">
<font size="9"/>
</textElement>
<textFieldExpression><![CDATA[($P{first_column}.equals("first_column") ? "First Column" : ($P{first_column}.equals("second_column") ? "Second Column" : ""))]]></textFieldExpression>
</textField>

String comparison in Java is done through the equals() method. This post explains it.
Assuming you have java.lang.String-based parameters you could do:
($P{first_column}.equals("second_column") ? "Second Column" : ($P{first_column}.equals("third_column") ? "Third Column" : ""))

Related

How to show dropdown in excel using jrxml (jasper api)?

I am new to jasper . My project used jasper to create an excel template that has only column names (eg : Name , Age , Department , Location) which uses jrxml for fonts and alignment. [basically we used the for showing the column names]
User can download the template and they can enter the values they want.
Now in order to avoid user enter the details manually by entering values , I would like to give dropdowns in the template with some hard coded values .
For example for the field 'Location' , I can set values like 'Texas' , 'California', 'FortWorth' etc . I am not querying from DB for these values , I just want to hard code these in .jrxml . I have to create one more row where the Location column alone should have drop down values from which user can pick one and upload to my application
In the downloaded excel , I want a dropdown with the above values so that user can select instead of typing themselves.
Is there any way to put this in .jrxml . If that is not possible then give the code that can render these in a dropdown in excel.
My sample .jrxml for one field is
<staticText>
<reportElement mode="Opaque" x="684" y="0" width="114" height="20" backcolor="#808080">
</reportElement>
<box leftPadding="10">
<pen lineColor="#000000" />
<topPen lineWidth="0.5" />
<leftPen lineWidth="0.5" />
<bottomPen lineWidth="0.5" />
<rightPen lineWidth="0.5" />
</box>
<textElement>
<font size="10" isBold="true" />
</textElement>
<text><![CDATA[Location]]></text>
</staticText>
Please let me know if more details are required
I don't think that with current jasper api 6.0 this is possibile but with POI (that is already in your classpath) it is farily easy to add this after export.
First we export or JasperPrint print, to excel (include code since its best to remove empty rows, we will process with poi later, Exception handling is beyond this example)
JRXlsExporter exporter = new JRXlsExporter();
File outputFile = new File("excelTest.xls");
exporter.setExporterInput(new SimpleExporterInput(print));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputFile));
SimpleXlsReportConfiguration configuration = new SimpleXlsReportConfiguration();
configuration.setOnePagePerSheet(false);
configuration.setDetectCellType(true);
configuration.setCollapseRowSpan(false);
configuration.setWhitePageBackground(false);
configuration.setRemoveEmptySpaceBetweenColumns(true);
configuration.setRemoveEmptySpaceBetweenRows(true);
exporter.setConfiguration(configuration);
exporter.exportReport();
Now that the report is exported to excel, we re-open it with POI and add our data validation.
int rowCount = 50; //This will be discussed at end.
int cellWithDV = 1;
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(outputFile));
HSSFSheet sheet = workbook.getSheetAt(0);
CellRangeAddressList addressList = new CellRangeAddressList(1,rowCount, cellWithDV, cellWithDV);
DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(
new String[]{ "Texas" , "California", "FortWorth"});
DataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint);
dataValidation.setSuppressDropDownArrow(false);
sheet.addValidationData(dataValidation);
workbook.write(new FileOutputStream(outputFile));
workbook.close();
The rowCount can be achived by:
Querying the database again
Use a scriptlet that counts how many times beforeDetailEval() is called
Use POI to find the the last row.
Use maximum value in excel (2003) is 65536
Hope this helps

How to create user defined formula for user defined field

I have created one JasperReports report in iReport 4.5.0.
Here i have created one expression as:
<textField pattern="###0.0;-###0.0">
<reportElement x="248" y="3" width="46" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[( $F{salesdetails_LessWeight} == 0 ? $F{salesdetails_Weight} - ($F{salesdetails_LessWeight} * $F{salesdetails_Quantity}) : $F{salesdetails_WithPlasticWeight} - ($F{salesdetails_LessWeight} * $F{salesdetails_Quantity}) )]]></textFieldExpression>
</textField>
Here I need the sum(total) of this text field created above ,
How to do that?
In this case you would simply create a variable with the same expression, but with a operation of "SUM". You can change the reset type to specify a group or simply for the whole report.
You can then use that variable in the Text Field element, with the execution time of Report/Group/Now depending on your needs.
<variable name="SOSUM" class="java.lang.Double" calculation="Sum">
<variableExpression><![CDATA[$F{salesdetails_LessWeight} == 0 ? $F{salesdetails_Weight} - ($F{salesdetails_LessWeight} * $F{salesdetails_Quantity}) : $F{salesdetails_WithPlasticWeight} - ($F{salesdetails_LessWeight} * $F{salesdetails_Quantity}) ]]></variableExpression>
</variable>

Passing main parameter to sub-datasets in JasperStudio

i'm created a report with JasperStudio 5.5 that have many parameter defined in the main and a lot of sub-dataset (defined with tables) that required this parameters.
The situation:
/main/Parameters: myPar
/main/mySubDataSet1/
/main/mySubDataSet2/
...
/main/mySubDataSetN/
The sub-dataset need to use this parameter in her query: select * from Tab t where t.attr = $P!{myPar}
So, my problem is that the sub-dataset can't access at this main paramenter, all the time that i try compiled, the program send me "Parameter not found : myPar".
How i can do for use myPar in the sub-dataset?
p.s.: i read this thread Pass main dataset parameter to subdataset query (based on iReport) but without success...
Well, you need to fill subDataset parameters with values where you actually make use of them. In this case the table which lists items from your subDataset needs to declare the necessary parameters and assign the values of the report-level dataset parameters to them.
In jrxml it sounds:
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="mySubDataSet1" uuid="bbe7937c-a8f1-4838-811a-3f11ec1f8e35">
<datasetParameter name="myPar">
<datasetParameterExpression><![CDATA[$P{myPar}]]></datasetParameterExpression>
</datasetParameter>
<connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
</datasetRun>
...
</jr:table>
For detail:
<subDataset name="dsLines" uuid="a47307ff-90a8-476f-afd1-0fd8aa0517d0">
<parameter name="formalId" class="java.lang.String"/>
<queryString language="SQL">
<![CDATA[
SELECT s.formalid, sl.*
FROM salesorder s INNER JOIN salesorderline sl
ON (s.id = sl.salesorder_id)
WHERE s.formalid = $P{formalId}
]]>
</queryString>
<field name="qty" class="java.math.BigDecimal"/>
...
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="dsLines" uuid="3ef5ec78-ab18-4f44-88e6-f99f3eafac07">
<datasetParameter name="formalId">
<datasetParameterExpression><![CDATA[$F{formalid}]]></datasetParameterExpression>
</datasetParameter>
</datasetRun>
<jr:column width="29" uuid="f675a273-7ea6-4bd4-8a55-c7522dfea2a8">
...

how to put bold for certain word in textfield?

I have for writing essay in the report. I just want to bold some text in my verse. I have put <b></b> tag in text, but it does not work.
An example of what I want is "My first name is Jason and my last name is Michael". Anybody know about this?
Try surrounding the words you want to highlight with HTML <b></b> (bold) tags, and change the field content type to HTML
This work good:
"<style isBold='true' pdfFontName='Helvetica-Bold'>" + $F{data} + "</style>"
for input data from datasource, or
<style isBold="true" pdfFontName="Helvetica-Bold">Bolt text</style>
only for some static text.
For Text-field set properties Markup = styled.
I just changed Properties → Markup → HTML. It works.
The <b> </b> tags no longer work on text fields. Make sure that 'Styled text' is enabled for the text field and put this in the field expression.
<style isBold="true" pdfFontName="Helvetica-Bold">Text to be bold...</style>
The pdfFontName can be whatever you like.
If you are making text bold that is already in a string be sure to escape the above quotes with a backslash or use single quotes.
As an example, one of my expressions:
{
"<b>"+$F{bezeichnung}+"</b>"+" ("+$F{anzahlStimmen}+" "+$R{stimmenI18N}+")"
}
For example - first character of the word is RED
<textField pattern="">
<reportElement x="23" y="35" width="189" height="18" forecolor="#000000" uuid="dd8bc5b3-1dc9-4348-84c8-ff7993746830"/>
<textElement textAlignment="Center" verticalAlignment="Middle" markup="styled">
<font fontName="Apolonia" size="17" isBold="true"/>
</textElement>
<textFieldExpression><![CDATA["<style forecolor=\"red\">"+$F{L1_word}.substring(0,1)+"</style>"+$F{L1_word}.substring(1)]]></textFieldExpression>
</textField>

JasperReports: Error executing SQL statement for

This is the error I got while compiling the jrxml file:
Compiling to file... /home/moshe/NetBeansProjects/Billing/src/billing/report2.jasper
Compilation running time: 299!
Filling report...
Locale: English (India)
Time zone: Default
Error filling print... Error executing SQL statement for : report2
net.sf.jasperreports.engine.JRException: Error executing SQL statement for : report2
at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:143)
at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:686)
at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:606)
at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1277)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:897)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:841)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:58)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:417)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:247)
at com.jaspersoft.ireport.designer.compiler.IReportCompiler.run(IReportCompiler.java:877)
at org.openide.util.RequestProcessor$Task.run(Unknown Source)
at org.openide.util.RequestProcessor$Processor.run(Unknown Source)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to usenear '"temp_bill" temp_bill,      "customer_details" customer_details WHERE      temp_' at line 38
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
... 11 more
Print not filled. Try to use an EmptyDataSource...
As per the error message, I checked the line 38 in the xml file, it is:
<![CDATA[SELECT
temp_bill.`bill_number`AS temp_bill_bill_number,
temp_bill.`sl_no`AS temp_bill_sl_no,
temp_bill.`cust_id`AS temp_bill_cust_id,
temp_bill.`cust_name`AS temp_bill_cust_name,
temp_bill.`date`AS temp_bill_date,
temp_bill.`item_code`AS temp_bill_item_code,
temp_bill.`item_name`AS temp_bill_item_name,
temp_bill.`tax`AS temp_bill_tax,
temp_bill.`unit_price`AS temp_bill_unit_price,
temp_bill.`quantity`AS temp_bill_quantity,
temp_bill.`gross_value`AS temp_bill_gross_value,
temp_bill.`cash_discount`AS temp_bill_cash_discount,
temp_bill.`net_value`AS temp_bill_net_value,
temp_bill.`qty_discount`AS temp_bill_qty_discount,
temp_bill.`net_total`AS temp_bill_net_total,
temp_bill.`cess`AS temp_bill_cess,
temp_bill.`tot_tax`AS temp_bill_tot_tax,
temp_bill.`grand_total`AS temp_bill_grand_total,
temp_bill.`remarks`AS temp_bill_remarks,
temp_bill.`billingAddress`AS temp_bill_billingAddress,
temp_bill.`tot_in_words`AS temp_bill_tot_in_words,
temp_bill.`deliv_note_no`AS temp_bill_deliv_note_no,
//line 38 is the next line*************************
temp_bill.`deliv_note_date`AS temp_bill_deliv_note_date,
temp_bill.`purchase_order_no`AS temp_bill_purchase_order_no,
temp_bill.`purchase_order_date`AS temp_bill_purchase_order_date,
temp_bill.`despatch_document_no`AS temp_bill_despatch_document_no,
temp_bill.`despatch_document_date`AS temp_bill_despatch_document_date,
temp_bill.`terms_of_delivery`AS temp_bill_terms_of_delivery,
customer_details.`TIN`AS customer_details_TIN,
customer_details.`cstRegNo`AS customer_details_cstRegNo,
customer_details.`phone_land`AS customer_details_phone_land,
customer_details.`phone_mob`AS customer_details_phone_mob,
customer_details.`fax`AS customer_details_fax,
customer_details.`email`AS customer_details_email,
customer_details.`cust_id`AS customer_details_cust_id FROM
"temp_bill" temp_bill,
"customer_details" customer_details WHERE
temp_bill.`cust_id` = customer_details.`cust_id`]]>
As per the error messages I checked the line no: 38 in the xml file and i could not find any problem with query, I use NetBeans plugin to generate the report. This problem started after I changed the type of customer_details.TIN from bigint to varchar. I've checked the xml file and made sure the TIN is of type varchar
<textField>
<reportElement x="27" y="77" width="241" height="11"/>
<textElement textAlignment="Center" markup="none">
<font size="8"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{customer_details_TIN}]]></textFieldExpression>
</textField>
check the manual that corresponds to
your MySQL server version for the
right syntax to use near '"temp_bill"
temp_bill, "customer_details"
customer_details WHERE temp_' at
line 38
When MySql tell you to see at line 38, it means line 38 from the start of the SQL sentence
I think you should review this:
FROM "temp_bill" temp_bill,
"customer_details"
Are these quotation marks needed? try to remove them :)