Here is an Emp.xls Table :-
+-------+-------------+---------------+--------+
| EmpId | Name | Designation | Salary|
+-------+-------------+---------------+--------+
| 1.0 | Akon Roy | project led | 12000.0|
| 2.0 | Brey Deo | manager | 13000.0|
| 3.0 | Dean | delivery head | 14000.0|
| 4.0 | Clark | team led |155555.0|
+-------+-------------+---------------+--------+
My problem is that i want to create a PDF file in which the output will be like:-
Hello <name>,
here name can be any of the name from the Emp.xls record, given by the user . How to do solve this problem using iText and Apache poi .
My code is:
public static void main(String[] args) {
try {
FileInputStream inputFile = new FileInputStream("E:\\Emp.xls");
HSSFWorkbook workbook = new HSSFWorkbook(inputFile);
HSSFSheet sheet = workbook.getSheetAt(0);
//adding row iterator
Iterator<Row> rowitr = sheet.iterator();
OutputStream file = new FileOutputStream(new File("E:\\Test.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
document.add(new Paragraph("Hello World, iText"));
//document.add(new Paragraph("Dear "));
while(rowitr.hasNext()){
Row row = rowitr.next();
//adding cell iterator
Iterator<Cell> cellitr = row.iterator();
while(cellitr.hasNext()){
Cell cell = cellitr.next();
switch(cell.getCellType()){
case Cell.CELL_TYPE_STRING:
if(cell.getStringCellValue == "Dean")
document.add(new Chunk("Dear " cell.getStringCellValue()+ ","));
}
}
}
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
If it is not possible with iText then pleas suggest me any other open source API Any help is appreciated.
According to one of your comments to the original question, you
try to get cell value and compare with excel name field like:
switch(cell.getCellType())
{
case Cell.CELL_TYPE_STRING:
if (cell.getStringCellValue() == "Dean")
document.add(new Chunk(cell.getStringCellValue()));
Ie you use ==
for String
comparison.
This is something which hardly ever works because in Java ==
applied to objects checks whether the identical object instance is referenced on both sides. You, on the other hand, only want to check whether the String
instances on both sides represent the same sequence of characters. For this task, you should use the equals
method:
if ("Dean".equals(cell.getStringCellValue()))
(I also switched the operands to prevent NullPointerExceptions
if cell.getStringCellValue()
is null
for some reason.)
In general using ==
only makes sense for primitive data types and for objects which you know to be unique in what they represent, eg enum
objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.