How to custom ( style ) excel file with " exceljs " in Angular 7 - java

I'm using ExcelJS to export excel file from JSON, the export works good but I need to add some changes in the excel file likes: color - font - width and etc.
And also I'm asking if I can write in an excel file already customized with a model.
Here is the service :
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], { type: EXCEL_TYPE });
FileSaver.saveAs(data, fileName + '_export_' + EXCEL_EXTENSION);
}
And thats how I call it:
this.excelService.exportAsExcelFile(dealTable, 'deals');

To my knowledge styling is supported in SheetJS Pro.
You can also look into ExcelJS which is not a paid version, but is slightly buggy.

Related

translate kotlin to java

I'm using a screenshot library (in Github) and it is has been written in Kotlin(I don't know Kotlin very well).
<https://github.com/bolteu/screenshotty>
I don't know how to translate to Java a part of code.
in the read me file :
val screenshotResult = screenshotManager.makeScreenshot()
val subscription = screenshotResult.observe(
onSuccess = { processScreenshot(it) },
onError = { onMakeScreenshotFailed(it) }
)
It says that you can get a screenshot object from "it"?
how can I do that?
please help me...
and how can I translate this code to Java :
fun show(screenshot: Screenshot) {
val bitmap = when (screenshot) {
is ScreenshotBitmap -> screenshot.bitmap
}
screenshotPreview.setImageBitmap(bitmap)
}

Is there way to export all html table pagination data using jspdf and autotable in javascript

I am exporting HTML table data into PDF. I have a lot of data to export, therefore my HTML table has a pagination option. while exporting I am getting only data which is appearing on the JSP page. Other data which are on pagination is not fetching in PDF. Is there any way to get all HTML table pagination data? I must have to use pagination option in HTML table because Data may be too large.
function exportTableToPDF(filename,report_title) {
var doc = new jsPDF('p', 'pt','a4');
var header = function(data) {
if (data.pageCount > 1) {
return false;
}
else
{
doc.setFontSize(11);
//doc.setTextColor(200, 0, 255);
doc.setFontStyle('bold');
doc.text(report_title, data.settings.margin.left + 35, 60);
doc.text('<%=DateLib.getDateTimeNow()%>', data.settings.margin.left + 35, 80);
}
};
var totalPagesExp = '{total_pages_count_string}';
var footer = function(data) {
var str = 'Page ' + data.pageCount;
// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
str = str + ' of ' + totalPagesExp;
console.log('test');
}
doc.text(str, data.settings.margin.left, doc.internal.pageSize.height - 30);
};
var options = {
beforePageContent: header,
afterPageContent: footer,
pagesplit: true,
margin: {
top: 100
}
};
var elem = document.getElementById('datatable-1');
var data = doc.autoTableHtmlToJson(elem);
doc.autoTable(data.columns, data.rows, options);
// Total page number plugin only available in jspdf v1.0+
if (typeof doc.putTotalPages === 'function') {
doc.putTotalPages(totalPagesExp);
}
doc.save(filename);
}
This provided code only extract data which are appearing on JSP at that time. For example, if my HTML table on page 4 using the pagination option, this will extract only page 4 data.
All data might not exist locally. You could either create a way to fetch the data for the pdf as json or include it on page right away some other way.

How to download a file from AJAX request in Liferay serveResource(-, -) method

I have a requirement like: I am making an AJAX request to pass some data to server. In my server I am creating a file using that data.
"Now problem is the file is not getting downloaded to client-side".
(I am using Apache POI API to create excel file from the given data).
Can any one will help me to do this ?
Here is my code:
(Code to make AJAX request)
<script>
function downloadUploadedBacklogs () {
try {
var table_data = [];
var count = jQuery("#backlogTable tr:first td" ).length;
jQuery("#<portlet:namespace/>noOfColumns").val(count);
var index = 0;
jQuery('tr').each(function(){
var row_data = '';
jQuery('td', this).each(function(){
row_data += jQuery(this).text() + '=';
});
table_data.push(row_data+";");
});
jQuery("#<portlet:namespace/>backlogDataForDownload").val(table_data);
jQuery("#<portlet:namespace/>cmd").val("downloadUploadedBacklogs");
alert('cmd: ' + jQuery("#<portlet:namespace/>cmd").val());
var formData = jQuery('#<portlet:namespace/>backlogImportForm').serialize();
jQuery.ajax({
url:'<%=resourceURL%>',
data:formData,
type: "post",
success: function(data) {
}
});
alert('form submitted');
} catch(e) {
alert('eroor: ' + e);
}
};
</script>
Java code serveResource(-,-) method
/*
* serveResource(-, -) method to process the client request
*/
public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
String cmd = ParamUtil.getString(resourceRequest,"cmd");
System.out.println("**********************cmd*************"+cmd);
if(cmd!="") {
if("downloadUploadedBacklogs".equalsIgnoreCase(cmd)){
String backlogData = ParamUtil.getString(resourceRequest, "backlogDataForDownload");
ImportBulkDataUtil.downloadUploaded("Backlogs", resourceRequest,resourceResponse);
}
}
}
/
* ImportBulkDataUtil.downloadUploaded(-, -, -) method to create excel file
/
public static void downloadUploaded(String schema, ResourceRequest resourceRequest,ResourceResponse resourceResponse) {
String excelSheetName = ParamUtil.getString(resourceRequest,"excelSheetName");
try {
resourceResponse.setContentType("application/vnd.ms-excel");
resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+excelSheetName+"_Template.xls");
OutputStream outputStream=resourceResponse.getPortletOutputStream();
//converting the POI object as excel readble object
HSSFWorkbook objHSSFWorkbook=new HSSFWorkbook();
HSSFSheet objHSSFSheet=objHSSFWorkbook.createSheet(excelSheetName+"_Template");
//set the name of the workbook
Name name=objHSSFWorkbook.createName();
name.setNameName(excelSheetName+"_Template");
objHSSFSheet.autoSizeColumn((short)2);
// create freeze pane (locking) top row
objHSSFSheet.createFreezePane(0, 1);
// Setting column width
String excelData = StringPool.BLANK;
if((schema.equalsIgnoreCase("Backlogs"))){
System.out.println("Inside BacklogsCreation..........");
objHSSFSheet.setColumnWidth(0, 10000);
objHSSFSheet.setColumnWidth(1, 7000);
objHSSFSheet.setColumnWidth(2, 7000);
objHSSFSheet.setColumnWidth(3, 7000);
objHSSFSheet.setColumnWidth(4, 7000);
objHSSFSheet.setColumnWidth(5, 5000);
objHSSFSheet.setColumnWidth(6, 5000);
objHSSFSheet.setColumnWidth(7, 7000);
objHSSFSheet.setColumnWidth(8, 7000);
excelData = ParamUtil.getString(resourceRequest,"backlogDataForDownload");
}
System.out.println("downloadUploaded excelTableData: " + excelData);
// Header creation logic
HSSFRow objHSSFRowHeader = objHSSFSheet.createRow(0);
objHSSFRowHeader.setHeightInPoints((2*objHSSFSheet.getDefaultRowHeightInPoints()));
CellStyle objHssfCellStyleHeader = objHSSFWorkbook.createCellStyle();
objHssfCellStyleHeader.setFillBackgroundColor((short)135);
objHssfCellStyleHeader.setAlignment(objHssfCellStyleHeader.ALIGN_CENTER);
objHssfCellStyleHeader.setWrapText(true);
// Apply font styles to cell styles
HSSFFont objHssfFontHeader = objHSSFWorkbook.createFont();
objHssfFontHeader.setFontName("Arial");
objHssfFontHeader.setColor(HSSFColor.WHITE.index);
HSSFColor lightGrayHeader = setColor(objHSSFWorkbook,(byte) 0x00, (byte)0x20,(byte) 0x60);
objHssfCellStyleHeader.setFillForegroundColor(lightGrayHeader.getIndex());
objHssfCellStyleHeader.setFillPattern(CellStyle.SOLID_FOREGROUND);
objHssfFontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
objHssfFontHeader.setFontHeightInPoints((short)12);
objHssfCellStyleHeader.setFont(objHssfFontHeader);
objHssfCellStyleHeader.setWrapText(true);
// first column about Backlog title
HSSFCell objBacklogTitleCell = objHSSFRowHeader.createCell(0);
objBacklogTitleCell.setCellValue("Backlog");
objBacklogTitleCell.setCellStyle(objHssfCellStyleHeader);
// second column about Description
HSSFCell objBacklogDescCell = objHSSFRowHeader.createCell(1);
objBacklogDescCell.setCellValue("Description");
objBacklogDescCell.setCellStyle(objHssfCellStyleHeader);
// third column about Project
HSSFCell objProjectNameCell = objHSSFRowHeader.createCell(2);
objProjectNameCell.setCellValue("Project");
objProjectNameCell.setCellStyle(objHssfCellStyleHeader);
setComment("Project which the backlog belongs to", objProjectNameCell);
// fourth column about Category
HSSFCell objCategoryNameCell = objHSSFRowHeader.createCell(3);
objCategoryNameCell.setCellValue("Category");
objCategoryNameCell.setCellStyle(objHssfCellStyleHeader);
setComment("Category which the backlog belongs to (i.e. Bug, New Requirement, Enhancement)", objCategoryNameCell);
// fifth column about Group
HSSFCell objGroupNameCell = objHSSFRowHeader.createCell(4);
objGroupNameCell.setCellValue("Group");
objGroupNameCell.setCellStyle(objHssfCellStyleHeader);
setComment("Group which the backlog belongs to", objGroupNameCell);
// sixth column about Est. Start Date
HSSFCell objEstStartDtCell = objHSSFRowHeader.createCell(5);
objEstStartDtCell.setCellValue("Est. Start Date");
objEstStartDtCell.setCellStyle(objHssfCellStyleHeader);
setComment("Date Format: dd/mm/yyyy", objEstStartDtCell);
// seventh column about Est. End Date
HSSFCell objEstEndDtCell = objHSSFRowHeader.createCell(6);
objEstEndDtCell.setCellValue("Est. End Date");
objEstEndDtCell.setCellStyle(objHssfCellStyleHeader);
setComment("Date Format: dd/mm/yyyy", objEstEndDtCell);
// fifth column about Group
HSSFCell objStatusCell = objHSSFRowHeader.createCell(7);
objStatusCell.setCellValue("Status");
objStatusCell.setCellStyle(objHssfCellStyleHeader);
String excelTableDataRecords[] = excelData.split(";");
for(int i=1; i<excelTableDataRecords.length; i++) {
HSSFRow objHSSFRow = objHSSFSheet.createRow(i);
objHSSFRow.setHeightInPoints((2*objHSSFSheet.getDefaultRowHeightInPoints()));
excelTableDataRecords[i] = excelTableDataRecords[i].substring(0, (excelTableDataRecords[i].length()-2));
if(excelTableDataRecords[i].charAt(0) == ',') {
excelTableDataRecords[i] = excelTableDataRecords[i].substring(1, (excelTableDataRecords[i].length()));
}
String excelTableColumns[] = excelTableDataRecords[i].split("::");
for(int j=0; j<excelTableColumns.length; j++) {
// Apply font styles to cell styles
HSSFFont objHssfFont = objHSSFWorkbook.createFont();
objHssfFont.setFontName("Arial");
CellStyle objHssfCellStyle = objHSSFWorkbook.createCellStyle();
objHssfFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
objHssfFont.setColor(HSSFColor.BLACK.index);
objHssfFont.setFontHeightInPoints((short)10);
objHssfCellStyle.setWrapText(true);
objHssfCellStyle.setFont(objHssfFont);
// other column about Backlog title
HSSFCell objNewHSSFCellFirstNameAdd = objHSSFRow.createCell(j);
objNewHSSFCellFirstNameAdd.setCellValue(excelTableColumns[j]);
objNewHSSFCellFirstNameAdd.setCellStyle(objHssfCellStyle);
}
}
objHSSFWorkbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception raised in downloadUploaded() method to download uploaded excel data");
}
}
Can anyone help me ?
There could be 2 issues. Either you don't send file at all or ajax is not downloading it.
From your code I can see that you writing file in response's output stream so I suspect that part is working. Maybe you can open browser developer tool to see response from server if it contains data in response body.
Second part is complicated because from nature of JS (security reason) you cannot download directly in JS itself (download will not start itself).
You need to use either iframe and append file url into and submit form to start download
$("body").append("<iframe src='" + data.message + "' style='display: none;' ></iframe>");
or
you can use new HTML5 FileAPI to do this for you in one request. Just specify blob (responseType: 'blob') type for response, convert URL from response body, append it to href attribute of newly created anchor <a> element and click on it.
See this post for more details.
Hope that helps.
You can write the contents of the POI HSSFWorkbook to a ByteArrayOutputStream and then use the toByteArray() method of the stream in Liferay's PortletResponseUtil sendFile() method as follows:
PortletResponseUtil.sendFile(resourceRequest, resourceResponse, "FILENAME", byteStream.toByteArray(), "CONTENT_TYPE");
instead of writing directly to the resourceResponse.
However, probably for security reasons, (Javascript can not directly write files to a client) you can not do this via Ajax.
You could alternatively save the raw data that you calculate in your JS code to a hidden input and pass that to the server via a regular form submit.
I think it's just your ajax command whose don't follow requirements.
See jquery ajax documentation.
It's seems ajax jquery complains xml data download but it's not accordingly with excel data format.
Set the dataType to "text" in ajax and does the good MIME type before to send the generated file to client..it's make the excel file download to be interpreted by the browser as a real excel file.
just have the request as GET, return the bytestream of file in response and set the headers accordingly (depending on the format of you file excel/pdf) and then at client side just open the response in new tab the browser would start the file download.
Just call the following function with parameters :
url - where you want to request for file data - incase you want to
send some data pageIndex - div id where u want to append iframe
and than it will be deleted without # .
this.ajaxDownload = function(url, data,pageId) {
pageId = '#' + pageId;
if ($(pageId + ' #download_iframe').length == 0) {
$("<iframe id='download_iframe' style='display: none' src='about:blank'></iframe>").appendTo(pageId);
}
var input = "<input type='hidden' name='requestJson' value='" + JSON.stringify(data) + "'>";
var iframe_html = "<html>"+
"<head>"+
"</head>"+
"<body>"+
"<form id='downloadForm' method='POST' action='" + url +"'>" +input+ "</form>" +
"</body>"+
"</html>";
var ifrm = $(pageId + ' #download_iframe')[0].contentWindow.document;
ifrm.open();
ifrm.write(iframe_html);
ifrm.close();
$(pageId + ' #download_iframe').contents().find("#downloadForm").submit();
}

Table of contents not added in pdf format using ASPOSE WORD , java

def gDataDir;
def index() {
gDataDir = "/home/sithapa/gitProject/aposeWord/documents/basics/";
topResultsTest();
}
def topResultsTest(){
Document main_src = new Document(gDataDir + "cover_page_toc.docx");
Document src3 = new Document(gDataDir + "our_testing_template.docx");
def String[] fields = ["Heading1","Subtitle1","Subtitle2"];
def Object[] values = ['This is a Heading','this is a subtitle1','\nthis is a subtitle2'];
src3.getMailMerge().execute(fields, values);
//Appending
main_src.appendDocument(src3, ImportFormatMode.KEEP_SOURCE_FORMATTING);
//Update the table of contents.
main_src.updateFields();
main_src.updatePageLayout();
main_src.save(gDataDir + "final_output.docx");
saveAsPDF(main_src)
}
def saveAsPDF(main_src){
//Document src = new Document(gDataDir + "final_output.docx");
//main_src.save(gDataDir + "simpleOpenSaveAsPDF_output.pdf", SaveFormat.PDF);
main_src.save(gDataDir + "Document.Doc2PdfSave Out.pdf");
}
Here the Table of contents is seen in .docx in a linux OS but not seen in Windows. TOC in pdf format is not seen in both OS.I have attached the required documents in this link:
enter link description here
I noted that your headings are in the document header. Please move these to the document body.
These headings are not saved in the PDF by default. You need to specify these in an instance of PdfSaveOptions.
// Set 2 levels of headings to appear in PDF
PdfSaveOptions so = new PdfSaveOptions();
so.getOutlineOptions().setHeadingsOutlineLevels(2);
// Specify the save options as parameter
document.save("output.pdf", so);
I work for Aspose as Developer Evangelist.

Jsoup transform my javascript string into a single line

I am having trouble with the .append function in Jsoup. I am appending my simple Javascript file response string to a Jsoup Element. But after appending my response transforms into a single line which is hurting me a lot.
My string is like this
(function () {
var count = 0;
var root = this;
var require = root.require;
//var require = cordova.require;
require.config({
config: {
text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications
useXhr: function (url, protocol, hostname, port) {
//console.log("text.useXhr request came from : " + url + ", " + protocol + " and " + hostname);
return true;
//return true if you want to allow this url, given that the
//text plugin thinks the request is coming from protocol, hostname, port.
}
},
'is': {
isBundled: true
}
},
waitSeconds: 45,
baseUrl: 'scripts/app',
deps: ["app"],
BUt after appending to a Element it will become
(function () { var count = 0; var root = this; var require = root.require; //var require = cordova.require; require.config({ config: { text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications useXhr: function (url, protocol, hostname, port) { //console.log("text.useXhr request came from : " +
My Code is for this
String temp=script.attr("src");
temp=temp.replace("/"+Heirarchy, DomainName+"/"+Heirarchy.toLowerCase());
script.attr("src", temp);
script.removeAttr("data-main");
script.removeAttr("async");
String innerHtml="</script>\n<script>\n"+old_configString;
script.append(innerHtml);
old_configString is my Javascript response String....
You should use a DataNode for adding scripts or styles.
script.after(new DataNode("<script>" + old_configString + "</script>", "http://domain.tld/path"));

Categories

Resources