Not able to download created excel using Java - java

Please check my code. There is no error. But still, I am not getting any excel downloaded. The console also shows no error and the sysout also shows the correct sizes of lists. 9 row data is coming from dao to this tpaAuthList. Please help.
#RequestMapping(value = "downloadTpaPreAuthExcel", method = RequestMethod.POST)
public void downloadTpaPreAuthExcel(#RequestParam("typevalue") String typevalue,
#RequestParam("idtypevalue") String idtypevalue, HttpServletRequest request,HttpServletResponse response, HttpSession session) {
Map<String, Object> map = new HashMap<String, Object>();
List<TpaPreAuthModel> tpaAuthList;
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=TpaPreAuth.xls");
try {
tpaAuthList = tpaPreAuthService.getTpaPreAuthSearchDataForExcel(typevalue,idtypevalue);
System.out.println("tpaAuthList size in method-->"+tpaAuthList.size());
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("DataSheet");
Map<String, Object[]> data = new LinkedHashMap<>();
data.put(String.valueOf(1), new Object[]{" TPA PRE AUTH LIST"});
data.put(String.valueOf(2), new Object[]{""});
data.put(String.valueOf(3), new Object[]{""});
int i = 5;
data.put("4", new Object[]{"Transaction ID", "Patient Name", "Hospital Name", "Pre Auth Date", "RGHS Card No", "Minutes Elapsed"});
for (TpaPreAuthModel listBean : tpaAuthList) {
data.put(String.valueOf(i), new Object[]{1,2,3,4,5,6});
i++;
}
System.out.println("For loop ended--");
Set<String> keyset = data.keySet();
int rownum = 0;
System.out.println("keyset size-->"+keyset.size());
for (String key : keyset) {
HSSFRow row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
HSSFCell cell = row.createCell(cellnum++);
if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
} else if (obj instanceof Long) {
cell.setCellValue((Long) obj);
}
}
}
System.out.println("Ket set for loop ended--");
OutputStream outputStream = response.getOutputStream();
System.out.println("Outstream--");
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}

Close workbook before it become file. See https://poi.apache.org/apidocs/dev/org/apache/poi/hssf/usermodel/HSSFWorkbook.html#close--
For better
HSSFWorkbook workbook = null;
try {
workbook = ...
//....
} catch (IOException ex) {
//...
}finally {
workbook.close();
}

You could try this:
#RequestMapping(value = "downloadTpaPreAuthExcel", method = RequestMethod.GET)
public Callable<ResponseEntity<StreamingResponseBody>> downloadTpaPreAuthExcel(
#RequestParam("typevalue") String typevalue,
#RequestParam("idtypevalue") String idtypevalue
) {
return new Callable<ResponseEntity<StreamingResponseBody>>() {
#Override
public ResponseEntity<StreamingResponseBody> call() throws Exception {
return toResponseBody(new Supplier<Workbook>() {
#Override
public Workbook get() {
Map<String, Object> map = new HashMap<String, Object>();
List<TpaPreAuthModel> tpaAuthList;
try {
tpaAuthList = tpaPreAuthService.getTpaPreAuthSearchDataForExcel(typevalue, idtypevalue);
System.out.println("tpaAuthList size in method-->" + tpaAuthList.size());
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("DataSheet");
Map<String, Object[]> data = new LinkedHashMap<>();
data.put(String.valueOf(1), new Object[] { " TPA PRE AUTH LIST" });
data.put(String.valueOf(2), new Object[] { "" });
data.put(String.valueOf(3), new Object[] { "" });
int i = 5;
data.put("4", new Object[] { "Transaction ID", "Patient Name", "Hospital Name",
"Pre Auth Date", "RGHS Card No", "Minutes Elapsed" });
for (TpaPreAuthModel listBean : tpaAuthList) {
data.put(String.valueOf(i), new Object[] { 1, 2, 3, 4, 5, 6 });
i++;
}
System.out.println("For loop ended--");
Set<String> keyset = data.keySet();
int rownum = 0;
System.out.println("keyset size-->" + keyset.size());
for (String key : keyset) {
HSSFRow row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
HSSFCell cell = row.createCell(cellnum++);
if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
} else if (obj instanceof Long) {
cell.setCellValue((Long) obj);
}
}
}
System.out.println("Ket set for loop ended--");
return workbook;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}, "TpaPreAuth.xlsx");
}
};
}
private ResponseEntity<StreamingResponseBody> toResponseBody(Supplier<Workbook> workbookSupplier, String fileName) {
Workbook workbook = workbookSupplier.get();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.body(new StreamingResponseBody() {
#Override
public void writeTo(OutputStream outputStream) throws IOException {
if (workbook != null) {
try (Workbook workbookRef = workbook) {
workbook.write(outputStream);
if (workbook instanceof SXSSFWorkbook ) {
((SXSSFWorkbook) workbook).dispose();
}
} finally {
if (workbook instanceof SXSSFWorkbook ) {
((SXSSFWorkbook) workbook).dispose();
}
}
}
}
}
);
}

Related

How to know excel is password protected or not

How to detect excel(xls and xlsx) file is password protected? is there any flag to check?
Note: there are 2 types to give password to the excel(xls/xlsx):
Password protected (excel->save as->Tools->general option )
Password encrypted (excel->File permissin->encrypt)
My code is working for only xls with password encrypted.
xls encrypted-EncryptedDocumentException -pass(proper exception )
xls password protected -IllegalArgumentException-fail(general exception)
xlsx encrypted-POIXMLException-fail(general exception)
xlsx password protected -POIXMLException-fail(general exception)
For above failed cases instead of general exception I want to improve this code.
Jars used:
poi-3.5-FINAL-20090928.jar
poi-3.7-20101029.jar
poi-ooxml-3.7-20101029.jar
public static String excelFileScanner(InputStream excelFileToScan,
String uploadFileExt) throws IOException {
String returnStatus = null;
try {
Workbook wb = null;// WorkbookFactory.create(excelFileToScan);
if (uploadFileExt.equalsIgnoreCase("xlsx")) {
wb = new XSSFWorkbook(excelFileToScan);
} else {
// POIFSFileSystem fs = new POIFSFileSystem(excelFileToScan);
wb = new HSSFWorkbook(excelFileToScan);
}
int noOfSheet = wb.getNumberOfSheets();
for (int i = 0; i < noOfSheet; i++) {
Sheet sheet = wb.getSheetAt(i);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return "malicious";
}
}
}
}
returnStatus = "valid";
} catch (POIXMLException ex1) {
// catch (InvalidFormatException ex1) {
returnStatus = ex1.getClass().getSimpleName();
if (ex1 != null && ex1.getCause() != null) {
System.out.println("reason: " + ex1.getCause().toString());
System.out.println("passwordprotected");
} else {
System.out.println("else block: " + ex1);
}
} catch (EncryptedDocumentException ex2) {
returnStatus = "passwordProtected";
} catch (Exception ex) {
returnStatus = ex.getMessage();
}
return returnStatus;
}
public static void main(String[] args) throws IOException {
try {
File folder = new File("/Desktop/Excel/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
String uploadFileExt = null;
String filename = file.getName();
int extnSeparatorIndex = filename.lastIndexOf(".");
if (extnSeparatorIndex != -1) {
if (extnSeparatorIndex != file.length() - 1) {
uploadFileExt = filename.substring(extnSeparatorIndex + 1);
}
// String uploadFileExt = file.getAbsolutePath();
InputStream fileUploaded = new FileInputStream(file.getAbsolutePath());
System.out.println("extension: " + uploadFileExt);
String returnStatus= PasswordExcelRead.excelFileScanner(fileUploaded, uploadFileExt);
System.out.println("Final: " + returnStatus);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Normally you would catch EncryptedDocumentException to check whether a file is password protected or not:
InputStream input = ...
Workbook wb;
try {
wb = WorkbookFactory.create(input)
} catch (EncryptedDocumentException e) {
// password protected
}

Selenium java Maven how to execute Testcase with fillo qry data driven framework

Testcase file. Testcase with fillo query data driven
Suppose when the query (String qry="Select * from Sheet1 where ACC='M' and GEN='F'";) returns 5 data rows for one test case and i want to use the same qry for the next case but with different data row
public class Testcases {
public WebDriver driver;
Fillo fillo;
static ExtentReports report;
ExtentTest test;
//String PAGE_URL = "Your_page_Url";
#BeforeClass public static void allTestsPrep(){
report = new ExtentReports("Report.html",true);
}
#AfterClass public static void allTestCleanUp() {
report.flush();
}
#Before
public void setUp() {
String browserName = getParameter("browser");
if (browserName.equalsIgnoreCase("chrome")){
driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();}
else if (browserName.equalsIgnoreCase("ie")) {
driver = new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// driver.get(PAGE_URL);
}
#Test
public void Testcase001() throws FilloException, InterruptedException {
String qry="Select * from Sheet1 where ACC='M' and GEN='F'";
test = report.startTest("Testcase 1 - Test findpage");
Useragreement usragr = new Useragreement(driver);
usragr.CheckboxSelectall();
test.log(LogStatus.PASS, "VERIFIED");//report
}
#After
public void close() {
driver.close();
test = null;
}
private String getParameter(String name) {
String value = System.getProperty(name);
if (value == null)
throw new RuntimeException(name + " is not a parameter!");
if (value.isEmpty())
throw new RuntimeException(name + " is empty!");
return value;
}
}
Fillo file
Now the code will be `FILLO.inputText(Phone_Number,"Pno",qry)``;
public class FILLOAPP {
public static String getTestValue(String fieldName, String qry) throws FilloException{
String testString=xlTesting(fieldName,qry);
return testString;
}
public static String xlTesting(String fieldName, String qry) throws FilloException{
String testval=null;
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("resources/TestData.xlsx");
String sqry=qry;
Recordset recordset=connection.executeQuery(sqry);
while(recordset.next()){
ArrayList<String> dataColl=recordset.getFieldNames();
Iterator<String> dataIterator=dataColl.iterator();
while(dataIterator.hasNext()){
for (int i=0;i<=dataColl.size()-1;i++){
String data=dataIterator.next();
String dataVal=recordset.getField(data);
if (data.equalsIgnoreCase(fieldName)){
String testData=dataColl.get(i);
String testValue= recordset.getField(testData);
testval=testValue;
}
}
break;
}
}
recordset.close();
connection.close();
return testval;
}
public static void inputText(WebElement driver, String fieldName, String qry) throws FilloException{
String fval=getTestValue(fieldName, qry);
driver.sendKeys(fval);
}
}
public String dataRead(String sheetname, String testcaseid, String header) throws IOException {
String value = null;
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
book = new XSSFWorkbook(fis);
sheet = book.getSheet(sheetname);
int lastRowNum = sheet.getLastRowNum();
// System.out.println(lastRowNum);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(lastCellNum);
for (int i = 0; i < lastRowNum; i++) {
for (int j = 1; j < lastCellNum; j++) {
Map<String, Map<String, String>> excelmap = new HashMap<String, Map<String, String>>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(j).toString(), sheet.getRow(i + 1).getCell(j).toString());
excelmap.put(sheet.getRow(i + 1).getCell(0).toString(), map);
if (excelmap.containsKey(testcaseid)) {
Map<String, String> w = excelmap.get(testcaseid);
if (map.containsKey(header)) {
value = w.get(header).toString();
}
}
}
}
} catch (Exception E) {
}
return value;
}
public void excelWrite(String sheetname, String testcaseid, int columnno, String value) throws Throwable {
File file = new File(TESTDATA_SHEET_PATH);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetname);
// sheetnoOfColumns = sheet.getRow(0).getPhysicalNumberOfCells();
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i < lastRowNum; i++) {
Map<Map<String, String>, String> excelmap = new HashMap<Map<String, String>, String>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(0).toString(), sheet.getRow(i + 1).getCell(0).toString());
if (map.containsValue(testcaseid)) {
excelmap.put(map, value);
String w = map.get("TestCase ID");
Map<String, String> fin = new HashMap<String, String>();
fin.put(w, value);
XSSFRow row = sheet.getRow(i + 1);
Cell createcell = row.createCell(columnno);
createcell.setCellValue(value);
}
}
FileOutputStream fileOut = new FileOutputStream(TESTDATA_SHEET_PATH);
workbook.write(fileOut);
fis.close();
fileOut.close();
}
public Map ReadExcelExecution() throws Throwable {
LinkedHashMap<String, Object[]> map = new LinkedHashMap<String, Object[]>();
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("IssuePolicy");
int TotalRow = sheet.getLastRowNum();
int noOfColumns = (sheet.getRow(0).getPhysicalNumberOfCells() - 1);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(TotalRow);
// System.out.println(noOfColumns);
// System.out.println(lastCellNum);
map.put("1",
new Object[] { "TestCase ID", "PolicyNo", "IssueDate", "Accumulated Value", "GMWB Type",
"MAWA/2LMAWA", "Remaining MAWA", "Protected Income Payment", "Accumulated Value DOD",
"DataComparison", "Comments" });
for (int i = 1; i <= TotalRow; i++) {
{
String testcaseid = sheet.getRow(i).getCell(0).toString();
String policyno = sheet.getRow(i).getCell(noOfColumns).toString();
String issuedate = sheet.getRow(i).getCell(2).toString();
String values = null;
map.put(testcaseid, new Object[] { testcaseid, policyno, issuedate, values, values, values, values,
values, values, values, values });
}
}
} catch (Exception E) {
}
return map;
}
public void writinginInputFile(String sheetname, Map mapvalue) throws Throwable {
// write excel file and file name is SaveTestNGResultToExcel.xls
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.createSheet(sheetname);
keyset = mapvalue.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = (Object[]) ReadExcelExecution().get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(TESTDATA_SHEET_PATH));
wb.write(out);
out.close();
System.out.println("Successfully saved Selenium WebDriver TestNG result to Excel File!!!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
}
package seleniumproject;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Multiplewindowpopup {
public static void main(String[] args) {
WebDriver driver;
String Userdir = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver",Userdir+"\\Driver\\chromedriver.exe");
driver = new ChromeDriver(); // launch chrome
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("http://www.popuptest.com/goodpopups.html");
//find ID of the 2nd link
driver.findElement(By.linkText("Good PopUp #2")).click();
Set<String> windowhandler = driver.getWindowHandles();
Iterator<String> myiterator = windowhandler.iterator();
////////////// //how to get index of parent and child window ???
//now we have two window IDs and moving the window from parent to child.
driver.switchTo().window(childWindow);
System.out.println("child window title"+driver.getTitle());
//closing the child window
driver.close();
// comming back to parentwindow
driver.switchTo().window(parentWindow);
System.out.println("parent window title"+driver.getTitle());
}
}

read json data to excel

I have a JSON file in the below format.
{
"applications": [
{
"author": "Appriss, Inc.",
"rating": 4.5,
"isAvailable": true,
"isRecommended": null,
"isEndorsed": false,
"id": "WfIABNya87qyAWABoDivFQ",
"app_name": "MobilePatrol Public Safety App",
"icon_path": "org_5945/android_market_62834/appIcon.png",
"custom_metadata": {
"title": null,
"description": null,
"projects": null,
"category": [
100
],
"user_segment": [
200
],
"aboutApp": null,
"tablet_1_description": null,
"tablet_2_description": null,
"tablet_3_description": null,
"tablet_4_description": null,
"tablet_5_description": null,
"screenshot_1_description": null,
"screenshot_2_description": null,
"screenshot_3_description": null,
"screenshot_4_description": null,
"screenshot_5_description": null,
"endorsement": null,
"developer_description": null,
"developer_website": null
},
"operating_system": "ANDROID",
"app_psk": 62834
},
}
I want to read few of data(like author,rating,app_name etc) into an excel in the form of key/value pair using java. Written below code.
public class JsonParseTest {
private static List<String> header = new ArrayList<String>();
private static List<Row> rows = new ArrayList<Row>();
private static Row row ;-- not able to instantiate this
private static int rowsSize;
public static List<String> getHeader() {
return header;
}
public static List<Row> getRows() {
return rows;
}
public static void main(String[] args) throws IOException, ParseException {
try {
// 1.read the json file
JSONObject jsonObject = readJson();
//2.iterate json file
for (Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext(); ) {
String header = (String) iterator.next();
short type = getType(jsonObject, header);
if (type == (short) 2) {
createHeader(header);
addFieldToRow(String.valueOf(jsonObject.get(header)), header);
}
}
createExcelFile();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
public static void iterateJsonObject(JSONObject jsonObject, String header) {
for (Iterator outerIterate = jsonObject.keySet().iterator(); outerIterate.hasNext(); ) {
String key = (String) outerIterate.next();
short type = getType(jsonObject, key);
if (type == (short) 2) {
createHeader(header);
addFieldToRow(String.valueOf(jsonObject.get(key)), key);
}
}
}
public static void iteratorJsonArray(JSONArray jsonArray, String header) {
if (jsonArray != null) {
int index = 0;
for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) {
List<String> beforeItrFields = new ArrayList<String>();
for (String field : ((Object) row).getField()) {
beforeItrFields.add("");
}
if (index == 0) {
rowsSize = getRows().size();
}
JSONObject jsonObject = (JSONObject) iterator.next();
iterateJsonObject(jsonObject, header);
if (!getRows().contains(row)) {
getRows().add(row);
}
reInitializeObj(row);
((Object) row).setField(beforeItrFields);
index++;
} }}
public static void reInitializeObj(Object o) {
if (o instanceof Row) {
row = null;
row = new Row();
}
}
//0:jsonObject,1:jsonArray ,2:key/value
public static Short getType(JSONObject jsonObject, String key) {
if (jsonObject.get(key) instanceof JSONObject)
return (short) 0;
else if (jsonObject.get(key) instanceof JSONArray)
return (short) 1;
else
return (short) 2;
}
public static void createHeader(String key) {
if (!getHeader().contains(key))
getHeader().add(key);
}
public static void addFieldToRow(String value, String key) {
row.addField(value);
}
public static JSONObject readJson() throws IOException, ParseException {
String filePath = "C:\\Users\\skond2\\Desktop\\JSON Files\\PSEID123_APPS.json";
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
return (JSONObject) jsonParser.parse(reader);
}
public static void createExcelFile() throws IOException, IllegalAccessException, InstantiationException {
FileOutputStream fileOut = new FileOutputStream("Apps.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("work log");
HSSFRow row1 = worksheet.createRow((short) 0);
short index = 0;
//create header
for (String header : getHeader()) {
HSSFCell cellA1 = row1.createCell(index);
cellA1.setCellValue(header);
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);
index++;
}
//create rows
index = 1;
for (Row row : getRows()) {
HSSFRow excelRow = worksheet.createRow(index);
short flag = 0;
for (String field : row.getField()) {
HSSFCell cellA1 = excelRow.createCell(flag);
cellA1.setCellValue(field);
flag++;
}
index++;
}
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
}
}
I'm getting errors at getField, addField methods of Row interface. First thing, is it correct declaration? private static Row row =new Row();
Row is from org.apache.poi.ss.usermodel.Row;
You can use the famous Apache POI for creating excel files. It is available here with documentation links. Your question is very general. You should try to do it on your own and get back to stackoverflow when you have a precise programming question.
Your problem can be broken down into the following 3 parts
Parse the JSON
Read the required values
Write the data in excel
For the first part you can use the any of the wide range of JSON parsing APIs and can also refer to this question
For the second part, once you get the data into your code, you need to be able to read through it, for this you'd need to be able to traverse through the Object that you'll get by using the above mentioned API.
And for the last part, you can simply write the output on a file in CSV format and open it in Excel.
This answer may seem vague, please comment if you need clarification

How can change the name of generated with JasperReports pdf file?

When I download a pdf file generated with JasperReports, its name is document.pdf.
I tried to set name with JasperPrint.setName(); but it doesn't work.
How can I change solve the task?
public class JaspereQueCaMarche {
public static enum Export {
PDF, HTML
};
private String cheminSource;
private JasperReport jasperReport;
private String nomRapport;
private List<ParametreJasper> parametres = new ArrayList<ParametreJasper>();
private static List<JaspereQueCaMarche> rapports = new ArrayList<JaspereQueCaMarche>();
protected JaspereQueCaMarche() {
}
public String getCheminSource() {
return cheminSource;
}
public String getNomRapport() {
return nomRapport;
}
public List<ParametreJasper> getParametres() {
return parametres;
}
public ParametreJasper getParametre(String nom) {
for (ParametreJasper pa : this.parametres) {
if (pa.getNom().equals(nom)) {
return pa;
}
}
return null;
}
public static List<JaspereQueCaMarche> getRapports() {
return rapports;
}
public static void setRapports(List<JaspereQueCaMarche> rapports) {
JaspereQueCaMarche.rapports = rapports;
}
public static JaspereQueCaMarche getFromHashCode(int hash) {
for (JaspereQueCaMarche jp : JaspereQueCaMarche.getRapports()) {
if (jp.hashCode() == hash) {
return jp;
}
}
return null;
}
public static void chargerListe(String repertoire) {
for (final File fic : new File(repertoire).listFiles()) {
if (!fic.isDirectory() && fic.getName().endsWith(".jrxml")) {
long dateModifSource = fic.lastModified();
String nomJasper = fic.getAbsolutePath();
nomJasper = nomJasper.substring(0, nomJasper.length() - 5) + "jasper";
File jasper = new File(nomJasper);
long dateModifObjet = jasper.exists() ? jasper.lastModified() : 0;
JaspereQueCaMarche jp = new JaspereQueCaMarche();
jp.cheminSource = fic.getAbsolutePath();
jp.nomRapport = fic.getName();
JasperReport jr = (dateModifObjet < dateModifSource) ? jp.compilerRapport() : jp.chargerRapport(jasper);
if (jr != null) {
jp.jasperReport = jr;
jp.extraireParametres();
JaspereQueCaMarche.rapports.add(jp);
}
}
}
}
public static JaspereQueCaMarche getEtat(String nom) {
String jrxml = nom + ".jrxml";
for (JaspereQueCaMarche jqcm : JaspereQueCaMarche.rapports) {
if (jqcm.nomRapport.equals(jrxml)) {
return jqcm;
}
}
return null;
}
private void extraireParametres() {
org.jdom2.Document document = null;
Element racine;
SAXBuilder sxb = new SAXBuilder();
try {
document = sxb.build(new File(this.getCheminSource()));
} catch (Exception e) {
Log.getLogGeneral().msgtest("erreur xml", e);
}
racine = document.getRootElement();
#SuppressWarnings("rawtypes")
List listeParametres = racine.getChildren();
#SuppressWarnings("rawtypes")
Iterator it = listeParametres.iterator();
while (it.hasNext()) {
Element courant = (Element) it.next();
if (courant.getName().equals("parameter")) {
String nom = courant.getAttributeValue("name");
String classe = courant.getAttributeValue("class");
String valeurParDefaut = "";
String description = "";
List<?> details = courant.getChildren();
Iterator<?> itDetails = details.iterator();
while (itDetails.hasNext()) {
Element detail = (Element) itDetails.next();
if (detail.getName().equals("defaultValueExpression")) {
valeurParDefaut = detail.getText();
} else if detail.getName().equals("parameterDescription")) {
description = detail.getText();
}
}
ParametreJasper pj = new ParametreJasper(nom, description, classe, valeurParDefaut);
this.parametres.add(pj);
}
}
}
public JasperPrint genererRapport(String transporteurConnecte) {
return genererRapport(transporteurConnecte, new HashMap<String, Object>());
}
public JasperPrint genererRapport(String transporteurConnecte, HashMap<String, Object> parametres) {
Connection conn = null;
JasperPrint jasperPrint = null;
try {
conn = new ConnexionJDBC(transporteurConnecte).getInstance();
} catch (SQLException | ClassNotFoundException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("impossible d'obtenir une connexion", e);
}
try {
if (this.jasperReport != null) {
jasperPrint = JasperFillManager.fillReport(jasperReport, parametres, conn);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("erreur fillReport", e);
}
return jasperPrint;
}
public void exporterRapport(JasperPrint jasperPrint, OutputStream outputStream, String transporteurConnecte) {
exporterRapport(jasperPrint, Export.PDF, outputStream, transporteurConnecte);
}
public void exporterRapport(JasperPrint jasperPrint, Export format, OutputStream outputStream, String transporteurConnecte) {
try {
if (format == Export.PDF) {
JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest(" erreur exportReportToPdfStream", e);
}
}
public void sauvegarderRapport(JasperPrint jasperPrint, Export format, String emplacement, String transporteurConnecte) {
try {
if (format == Export.PDF) {
JasperExportManager.exportReportToPdfFile(jasperPrint, "test.pdf");
} else if (format == Export.HTML) {
JasperExportManager.exportReportToHtmlFile(jasperPrint, emplacement);
}
} catch (JRException e) {
Log.getMapLog().get(transporteurConnecte).msgtest("erreur exportReport", e);
}
}
protected JasperReport compilerRapport() {
JasperReport jr = null;
try {
String cheminRapportCompile = JasperCompileManager.compileReportToFile(this.cheminSource);
jr = chargerRapport(new File(cheminRapportCompile));
} catch (JRException e) {
Log.getLogGeneral().msgprod("Impossible de compiler le rapport " + this.cheminSource, e);
}
return jr;
}
protected JasperReport chargerRapport(File fJasper) {
JasperReport jr = null;
try {
jr = (JasperReport) JRLoader.loadObject(fJasper);
} catch (JRException e) {
Log.getLogGeneral().msgprod("Impossible de charger le rapport " + fJasper.getAbsolutePath(), e);
}
return jr;
}
}
You may use exportReportToPdfFile from JasperExportManager, (report being your JasperPrint object)
JasperExportManager.exportReportToPdfFile(report, fileName);
The question is not clear enough, If you're using servlet/JSF you can do it like this.
HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
httpServletResponse.addHeader("Content-disposition", "attachment; filename=report"+dateR+"_"+dateR1+".pdf");
ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);

How to serialize object to CSV file?

I want to write a Object into CSV file.
For XML we have XStream like this
So if i want to convert object to CSV do we have any such library ?
EDIT:
I want to pass my list of Bean to a method which should write all the fields of bean to CSV.
First, serialization is writing the object to a file 'as it is'. AFAIK, you cannot choose file formats and all. The serialized object (in a file) has its own 'file format'
If you want to write the contents of an object (or a list of objects) to a CSV file, you can do it yourself, it should not be complex.
Looks like Java CSV Library can do this, but I have not tried this myself.
EDIT: See following sample. This is by no way foolproof, but you can build on this.
//European countries use ";" as
//CSV separator because "," is their digit separator
private static final String CSV_SEPARATOR = ",";
private static void writeToCSV(ArrayList<Product> productList)
{
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("products.csv"), "UTF-8"));
for (Product product : productList)
{
StringBuffer oneLine = new StringBuffer();
oneLine.append(product.getId() <=0 ? "" : product.getId());
oneLine.append(CSV_SEPARATOR);
oneLine.append(product.getName().trim().length() == 0? "" : product.getName());
oneLine.append(CSV_SEPARATOR);
oneLine.append(product.getCostPrice() < 0 ? "" : product.getCostPrice());
oneLine.append(CSV_SEPARATOR);
oneLine.append(product.isVatApplicable() ? "Yes" : "No");
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
}
catch (UnsupportedEncodingException e) {}
catch (FileNotFoundException e){}
catch (IOException e){}
}
This is product (getters and setters hidden for readability):
class Product
{
private long id;
private String name;
private double costPrice;
private boolean vatApplicable;
}
And this is how I tested:
public static void main(String[] args)
{
ArrayList<Product> productList = new ArrayList<Product>();
productList.add(new Product(1, "Pen", 2.00, false));
productList.add(new Product(2, "TV", 300, true));
productList.add(new Product(3, "iPhone", 500, true));
writeToCSV(productList);
}
Hope this helps.
Cheers.
For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.
EDIT
According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !
By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.
I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.
Two options I just ran into:
http://sojo.sourceforge.net/
http://supercsv.sourceforge.net/
It would be interesting to have a csv serializer as it would take up the minimal space compared to other serializing method.
The closest support for java object to csv is stringutils provided by spring utils project
arrayToCommaDelimitedString(Object[] arr) but it is far from being a serializer.
Here is a simple utility which uses reflection to serialize value objects
public class CSVWriter
{
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
if(data.length==0)
{
return "";
}
Class classType = data[0].getClass();
StringBuilder builder = new StringBuilder();
Method[] methods = classType.getDeclaredMethods();
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get"))
{
builder.append(m.getName().substring(3)).append(',');
}
else if(m.getName().startsWith("is"))
{
builder.append(m.getName().substring(2)).append(',');
}
}
}
builder.deleteCharAt(builder.length()-1);
builder.append('\n');
for(Object d : data)
{
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get") || m.getName().startsWith("is"))
{
System.out.println(m.invoke(d).toString());
builder.append(m.invoke(d).toString()).append(',');
}
}
}
builder.append('\n');
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
public static boolean generateCSV(File csvFileName,Object[] data)
{
FileWriter fw = null;
try
{
fw = new FileWriter(csvFileName);
if(!csvFileName.exists())
csvFileName.createNewFile();
fw.write(produceCsvData(data));
fw.flush();
}
catch(Exception e)
{
System.out.println("Error while generating csv from data. Error message : " + e.getMessage());
e.printStackTrace();
return false;
}
finally
{
if(fw!=null)
{
try
{
fw.close();
}
catch(Exception e)
{
}
fw=null;
}
}
return true;
}
}
Here is an example value object
public class Product {
private String name;
private double price;
private int identifier;
private boolean isVatApplicable;
public Product(String name, double price, int identifier,
boolean isVatApplicable) {
super();
this.name = name;
this.price = price;
this.identifier = identifier;
this.isVatApplicable = isVatApplicable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public boolean isVatApplicable() {
return isVatApplicable;
}
public void setVatApplicable(boolean isVatApplicable) {
this.isVatApplicable = isVatApplicable;
}
}
and the code to run the util
public class TestCSV
{
public static void main(String... a)
{
Product[] list = new Product[5];
list[0] = new Product("dvd", 24.99, 967, true);
list[1] = new Product("pen", 4.99, 162, false);
list[2] = new Product("ipad", 624.99, 234, true);
list[3] = new Product("crayons", 4.99,127, false);
list[4] = new Product("laptop", 1444.99, 997, true);
CSVWriter.generateCSV(new File("C:\\products.csv"),list);
}
}
Output:
Name VatApplicable Price Identifier
dvd true 24.99 967
pen false 4.99 162
ipad true 624.99 234
crayons false 4.99 127
laptop true 1444.99 997
I wrote a simple class that uses OpenCSV and has two static public methods.
static public File toCSVFile(Object object, String path, String name) {
File pathFile = new File(path);
pathFile.mkdirs();
File returnFile = new File(path + name);
try {
CSVWriter writer = new CSVWriter(new FileWriter(returnFile));
writer.writeNext(new String[]{"Member Name in Code", "Stored Value", "Type of Value"});
for (Field field : object.getClass().getDeclaredFields()) {
writer.writeNext(new String[]{field.getName(), field.get(object).toString(), field.getType().getName()});
}
writer.flush();
writer.close();
return returnFile;
} catch (IOException e) {
Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
return null;
} catch (IllegalAccessException e) {
Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
return null;
}
}
static public void fromCSVFile(Object object, File file) {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] nextLine = reader.readNext(); // Ignore the first line.
while ((nextLine = reader.readNext()) != null) {
if (nextLine.length >= 2) {
try {
Field field = object.getClass().getDeclaredField(nextLine[0]);
Class<?> rClass = field.getType();
if (rClass == String.class) {
field.set(object, nextLine[1]);
} else if (rClass == int.class) {
field.set(object, Integer.parseInt(nextLine[1]));
} else if (rClass == boolean.class) {
field.set(object, Boolean.parseBoolean(nextLine[1]));
} else if (rClass == float.class) {
field.set(object, Float.parseFloat(nextLine[1]));
} else if (rClass == long.class) {
field.set(object, Long.parseLong(nextLine[1]));
} else if (rClass == short.class) {
field.set(object, Short.parseShort(nextLine[1]));
} else if (rClass == double.class) {
field.set(object, Double.parseDouble(nextLine[1]));
} else if (rClass == byte.class) {
field.set(object, Byte.parseByte(nextLine[1]));
} else if (rClass == char.class) {
field.set(object, nextLine[1].charAt(0));
} else {
Log.e("EasyStorage", "Easy Storage doesn't yet support extracting " + rClass.getSimpleName() + " from CSV files.");
}
} catch (NoSuchFieldException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IllegalAccessException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
}
} // Close if (nextLine.length >= 2)
} // Close while ((nextLine = reader.readNext()) != null)
} catch (FileNotFoundException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IOException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IllegalArgumentException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
}
}
I think with some simple recursion these methods could be modified to handle any Java object, but for me this was adequate.
Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.
I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.
Link: https://github.com/abhisoni96/dev-tools
Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.
You can use gererics to work for any class
public class FileUtils<T> {
public String createReport(String filePath, List<T> t) {
if (t.isEmpty()) {
return null;
}
List<String> reportData = new ArrayList<String>();
addDataToReport(t.get(0), reportData, 0);
for (T k : t) {
addDataToReport(k, reportData, 1);
}
return !dumpReport(filePath, reportData) ? null : filePath;
}
public static Boolean dumpReport(String filePath, List<String> lines) {
Boolean isFileCreated = false;
String[] dirs = filePath.split(File.separator);
String baseDir = "";
for (int i = 0; i < dirs.length - 1; i++) {
baseDir += " " + dirs[i];
}
baseDir = baseDir.replace(" ", "/");
File base = new File(baseDir);
base.mkdirs();
File file = new File(filePath);
try {
if (!file.exists())
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
return isFileCreated;
}
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), System.getProperty("file.encoding")))) {
for (String line : lines) {
writer.write(line + System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
void addDataToReport(T t, List<String> reportData, int index) {
String[] jsonObjectAsArray = new Gson().toJson(t).replace("{", "").replace("}", "").split(",\"");
StringBuilder row = new StringBuilder();
for (int i = 0; i < jsonObjectAsArray.length; i++) {
String str = jsonObjectAsArray[i];
str = str.replaceFirst(":", "_").split("_")[index];
if (i == 0) {
if (str != null) {
row.append(str.replace("\"", ""));
} else {
row.append("N/A");
}
} else {
if (str != null) {
row.append(", " + str.replace("\"", ""));
} else {
row.append(", N/A");
}
}
}
reportData.add(row.toString());
}

Categories