Creation of Csv File in Java and Downloading in Angular 4
Posted By : Ranjan Mondal | 26-Sep-2018
Introduction:
Full form of csv is Comma Separated Value. It is simple file format used to store data in tabular format, which is easy to read and store.
We can write programs in languages to read the data from csv and store in the tables or databases.
It is oftenlly used to make a report from existing data in database.
Following code is in java to create csv file from Java Dto.
public void userCsvDocument(String[] header, List<Usermanagementdto> userList , String fileName,
HttpServletRequest request, HttpServletResponse response) throws NullPointerException, Exception {
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName+".csv\"");
String firstLine = Arrays.stream(header).collect(Collectors.joining(",", "", "\n"));
StringBuilder lines = new StringBuilder(firstLine);
int serialNo = 0;
if(!Objects.isNull(userList) && !userList.isEmpty()){
for(UserManagementDto user : userList){
//LOGGER.info("Serial Number {}", serialNo);
lines.append(++serialNo).append(",").append(user.getId()).append(",");
String name = user.getUserType() == UserType.INDIVIDUAL ? user.getFirstName() + " " + user.getLastName()
: user.getCompanyName();
String kycDate = user.getIsKycVerified() ? user.getKycDate() == null ? "Not Known" : user.getKycDate().toString()
: "N.A";
lines.append(name).append(",").append(user.getPhoneCode() + " " + user.getMobileNumber()).append(",")
.append(user.getEmail()).append(",").append(user.getUserType()).append(",")
.append(user.getCreatedDate()).append(",").append(user.getName()).append(",")
.append(user.getCountryName()).append(",").append(user.getAmlStatus())
.append(",").append(user.getLastLogin())
.append(",").append(kycDate)
.append("\n");
}
}
try {
java.io.OutputStream outputStream = response.getOutputStream();
String outputResult = lines.toString();
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
to download in Angular 4, following is code. It will receive whole data from body and download using following code.
downloadCsvAllUser() {
this.csvSpinner = true;
let searchParams = this.userDataObj;
searchParams.size = this.csvPageSize;
searchParams.start = 1;
this.UserServiceDetails.downloadCsvAllUser(searchParams).subscribe(
data => {
let csvData = data['_body'] || '';
this.csvSpinner = false;
this.sharedService.downloadCSV(csvData,"User_List-" + new Date());
},
error => {
this.csvSpinner = false;
let errMsg = error.message ? error.message: error.status ? `${error.status} - ${error.statusText}` : "Server error";
this.toasterService.pop("error", "Error!", errMsg);
}
);
downloadCSV(csvData, fileName) {
var localblob = new Blob([csvData], { type: "text/csv" });
let dwldLink = document.createElement("a");
let url = window.URL.createObjectURL(localblob);
let isSafariBrowser =
navigator.userAgent.indexOf("Safari") != -1 &&
navigator.userAgent.indexOf("Chrome") == -1;
if (isSafariBrowser) {
dwldLink.setAttribute("target", "_blank");
}
dwldLink.setAttribute("href", url);
dwldLink.setAttribute("download", fileName + ".csv");
dwldLink.style.visibility = "hidden";
document.body.appendChild(dwldLink);
dwldLink.click();
document.body.removeChild(dwldLink);
}
code for service file in Angular 4, it will send whole body in which data is present.
downloadCsvAllUser(userDataObj) {
this.tenant = this.getTennatStorage();
let url = config.host + 'admin/users/csv/' + this.tenant;
return this.HttpClient.put(url, userDataObj);
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ranjan Mondal
Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.