I am using Sheetjs to write json content in the file. I am able to write into file and download. Most my report export intigrated with this an everything works.
But I have recently got new excel format which looks something like
I am not able to implement like this using sheetjs. I tried most of issue on GIT account and read about it ,but still nothing helped me.
Below is the generic code block for reference
public exportAsExcelFile(jsonint: any[], excelFileName: string,replaceMap:any,headerOrder: string[]): boolean {
var jsonData =this.replaceKeyInObjectArray(jsonint,replaceMap);
var orderedJSON = JSON.parse(JSON.stringify( jsonData, headerOrder, 10));
let worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(orderedJSON);
const workbook: XLSX.WorkBook = { Sheets: {'data': worksheet}, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook,{ bookType: 'xlsx', type: 'buffer' });
this.saveAsExcelFile(excelBuffer, excelFileName);
return true; }
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
})
FileSaver.saveAs(data, fileName + '-' + Util.getCurrDate("_") + EXCEL_EXTENSION); }
If someone know this help me out.Thanks in advance
Related
I have an API response where I'm getting data as comma separated values and not as JSON objects. I need to export this data into CSV file. Can someone please suggest a method to do this?
You could parse your data to a JSON-object:
const apiData: string = 'value1,value2,value3';
const data: string[] = apiData.split(',');
And then you could use a combination of xlsx and fileSaver
Pseudocode:
const worksheet: xlsx.WorkSheet = xlsx.utils.json_to_sheet(data);
const workbook: xlsx.WorkBook = {
Sheets: { [worksheetName]: worksheet },
SheetNames: [worksheetName]
};
const buffer = xlsx.write(workbook, { 'csv', type: 'array' });
const blob = new Blob([buffer], { type: 'text/comma-separated-values' });
fileSaver.saveAs(blob, 'filename.csv');
Ashamed to ask, but for resolving my problem I need to ask.
So, I have a problem with reading data from an excel file in my Angular project. The file is located in the assets folder.
I know how to get a file from the folder.
In app.component.ts inside ngOnInit I get a file:
ngOnInit() {
this.http.get('assets/dataTest.xlsx').subscribe((data: any) => {
console.log("get: " + data);
});
}
How I understand inside http.get I need to use code below:
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
console.log("READ " + e);
};
reader.readAsBinaryString(data);
But it does not work. I get an error:
ERROR TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.
Help me please with reading data from an excel file is located in the assets folder.
I suggest to use a library to parse the excel file.
See there an example of SheetJs:
/* <input type="file" (change)="onFileChange($event)" multiple="false" /> */
/* ... (within the component class definition) ... */
onFileChange(evt: any) {
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* save data */
this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));
};
reader.readAsBinaryString(target.files[0]);
}
i just solve the problem with this.
read() {
this.httpClient.get('assets/files/Report DTP.xls', { responseType: 'blob' })
.subscribe((data: any) => {
const reader: FileReader = new FileReader();
let dataJson1;
let dataJson2;
reader.onload = (e: any) => {
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname1: string = wb.SheetNames[1];
const ws1: XLSX.WorkSheet = wb.Sheets[wsname1];
/* grab second sheet */
const wsname2: string = wb.SheetNames[2];
const ws2: XLSX.WorkSheet = wb.Sheets[wsname2];
/* save data */
dataJson1 = XLSX.utils.sheet_to_json(ws1);
dataJson2 = XLSX.utils.sheet_to_json(ws2);
console.log(dataJson1);
};
reader.readAsBinaryString(data);
console.log(data);
});
}
I hope it helps you even though it's late :)
I was using Axios to download a file provided by a GET endpoint previously. The endpoint has changed and is now a POST, however the parameters are not required. I'm updating the original download method, but am getting a corrupted file returned.
downloadTemplate() {
axios.post(DOWNLOAD_TEMPLATE_URL,
{
responseType: 'blob',
headers: {
'Content-Disposition': "attachment; filename=template.xlsx",
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'template.xlsx');
document.body.appendChild(link);
link.click();
})
.catch((error) => console.log(error));
}
I'm not sure if the issue is with the responseType, headers, or how the response is handled or all of the above. I've tried various options with no luck so far. Any suggestions would be greatly appreciated!
I have been able to download the file using Postman so I know the file served by the endpoint is fine. I just can't sort out the params to do this in my React code.
Finally got it working! The post syntax in the code block for the question was not correct and also changed the responseType to "arraybuffer".
Working example below:
downloadTemplate() {
axios.post(DOWNLOAD_TEMPLATE_URL, null,
{
headers:
{
'Content-Disposition': "attachment; filename=template.xlsx",
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
},
responseType: 'arraybuffer',
}
).then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'template.xlsx');
document.body.appendChild(link);
link.click();
})
.catch((error) => console.log(error));
}
We can use the following code to export Excel files from the POST method. May it help someone and save time.
For API use .Net Core 2.2 and the method is below.
Note: When we create a FileStreamResult, Content-Disposition header for the response will contain the filename and the stream will come as an attachment.
Add the "Content-Disposition" to Cors at Startup file,
app.UseCors(b => b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials().WithExposedHeaders("Content-Disposition"));
I am using the EPplus package for generating the Excel file.
using OfficeOpenXml;
using OfficeOpenXml.Style;
public static MemoryStream InvoiceToExcel(List<InvoiceSearchDto> invoices)
{
var listOfFieldNames = typeof(InvoiceSearchDto).GetProperties().Select(f => f.Name).ToList();
int cellCounter = 1, recordIndex = 2;
var ms = new MemoryStream();
using (ExcelPackage package = new ExcelPackage(ms))
{
ExcelWorksheet worksheet;
worksheet = package.Workbook.Worksheets.Add("New HGS");
// Setting the properties of the first row
worksheet.Row(1).Height = 20;
worksheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
worksheet.Row(1).Style.Font.Bold = true;
// Header of the Excel sheet
foreach (string header in listOfFieldNames)
{
worksheet.Cells[1, cellCounter++].Value = header;
}
// Inserting the article data into excel
// sheet by using the for each loop
// As we have values to the first row
// we will start with second row
foreach (InvoiceSearchDto invoice in invoices)
{
worksheet.Cells[recordIndex, 1].Value = invoice.CompanyName;
worksheet.Cells[recordIndex, 2].Value = invoice.CustomerNo;
worksheet.Cells[recordIndex, 3].Value = invoice.DocumentNumber;
worksheet.Cells[recordIndex, 4].Value = invoice.BillingPeriodStartDate.ToString("YYYY-MM-DD");
worksheet.Cells[recordIndex, 5].Value = invoice.BillingPeriodEndDate.ToString("YYYY-MM-DD");
worksheet.Cells[recordIndex, 6].Value = invoice.DateOfInvoice.ToString("YYYY-MM-DD");
worksheet.Cells[recordIndex, 7].Value = invoice.ExpirationDate.ToString("YYYY-MM-DD");
worksheet.Cells[recordIndex, 8].Value = invoice.Amount;
worksheet.Cells[recordIndex, 9].Value = invoice.InvoiceStatusText;
recordIndex++;
}
// By default, the column width is not
// set to auto fit for the content
// of the range, so we are using
// AutoFit() method here.
worksheet.Column(1).AutoFit();
worksheet.Column(2).AutoFit();
worksheet.Column(3).AutoFit();
worksheet.Column(4).AutoFit();
worksheet.Column(5).AutoFit();
worksheet.Column(6).AutoFit();
worksheet.Column(7).AutoFit();
worksheet.Column(8).AutoFit();
worksheet.Column(9).AutoFit();
package.Save();
}
ms.Position = 0;
return ms;
}
The Action Method code is as below
[HttpPost]
[Route("[action]")]
public IActionResult GetInvoiceWithExcel([FromBody]SearchInvoice searchInvoice)
{
try
{
if (!string.IsNullOrEmpty(searchInvoice.InvoiceDateFrom))
{
searchInvoice.DateFrom = Convert.ToDateTime(searchInvoice.InvoiceDateFrom);
}
if (!string.IsNullOrEmpty(searchInvoice.InvoiceDateTo))
{
searchInvoice.DateTo = Convert.ToDateTime(searchInvoice.InvoiceDateTo);
}
var invoices = invoiceBatchService.GetAllForExcel(searchInvoice.PagingParams, searchInvoice, searchInvoice.FilterObject);
if (invoices != null)
{
MemoryStream invoiceStream = ExcelConverter.InvoiceToExcel(invoices);
var contentType = "application/octet-stream";
var fileName = "Invoice.xlsx";
return File(invoiceStream, contentType, fileName);
}
else
{
ResponseModel.Notification = Utility.CreateNotification("Not Found Anything", Enums.NotificationType.Warning);
return NotFound(ResponseModel);
}
}
catch (Exception ex)
{
NLogger.LogError(ex, "Get Invoice With Excel");
ResponseModel.Notification = Utility.CreateNotification(Helpers.ExceptionMessage(ex), Enums.NotificationType.Error);
return StatusCode(500, ResponseModel);
}
}
Finally the React and axois code as below.
the Service code:
return http.post(
API_BASE_URL + "/Invoice/GetInvoiceWithExcel",
searchInvoice,
{
headers: getHeaders(), // for token and others
responseType: 'blob' // **don't forget to add this**
}
);
};
And the Action method Code is below. Here I use the "file-saver" package to download the file.
import { saveAs } from 'file-saver';
export const getInvoiceWithExcel = invoiceInfo => {
return dispatch => {
dispatch({
type: LOADING_ON
});
InvoiceService.getInvoiceWithExcel(invoiceInfo)
.then(res => {
console.log(res);
let filename = res.headers['content-disposition']
.split(';')
.find((n) => n.includes('filename='))
.replace('filename=', '')
.trim();
let url = window.URL
.createObjectURL(new Blob([res.data]));
saveAs(url, filename);
dispatch({
type: GET_INVOICE_EXCEL_SUCCESS,
payload: ""
});
dispatch({
type: LOADING_OFF
});
dispatch({
type: ON_NOTIFY,
payload: {
...res.data.notification
}
});
})
.catch(err => {
dispatch({
type: GET_INVOICE_EXCEL_FAILED
});
dispatch({
type: LOADING_OFF
});
dispatch({
type: ON_NOTIFY,
payload: {
...Utility.errorResponseProcess(err.response)
}
});
});
};
};
I have to convert one of the sheets from an xslx to csv, for that I use the following code:
url = 'routes/file.xlsx';
const workbook = XLSX.readFile(url);
const csv = XLSX.utils.sheet_to_csv(workbook.Sheets.files);
XLSX.writeFile(csv, 'file.csv');
But when I execute it, I get that error, some idea of what to do.
Thank you
First of all generate your CSV content:
var table = document.getElementById(id);
var wb = XLSX.utils.table_to_book(table, { sheet: "Sheet JS" });
var ws1 = wb.Sheets[wb.SheetNames[0]];
var csv = XLSX.utils.sheet_to_csv(ws1, { strip: true });
download_file(csv, 'my_csv.csv', 'text/csv;encoding:utf-8');
And then the download_file function credit to Javascript: set filename to be downloaded:
function download_file(content, fileName, mimeType) {
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([content], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
}
Hi I am go for the generate excel file form the array but I am not getting successes. I am work using node.js and I am use npm package for generate excel file but I am not getting any data in excel file. excel is generate but not getting any type of data in my file. so any one know where is my mistake then please let me know how can fix it.
This is my array and query =>
var XLSX = require('xlsx');
var Array = [];
Array.push({
username: 'Carakc',
fullName: 'Crack',
followingCount: 2655,
followerCount: 466,
biography: 'I am new man'
},
{
username: 'mahi',
fullName: 'Fit',
followingCount: 3011,
followerCount: 385,
biography: 'hello everyone!'
})
app.get(prefix + '/GetFollowersInExcel', function (req, res, next) {
var ws = XLSX.utils.json_to_sheet(Array);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Followres");
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
res.end(wbout, 'binary');
}
});
}
});
})
This is my service code =>
GetFollowersInExcel: function (InstaId) {
return $http({
method: "GET",
url: ONURL + "GetFollowersInExcel",
responseType: "arraybuffer",
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).then(function (data, status, xhr) {
debugger;
if (data.data.byteLength > 0) {
var file = new Blob([data.data], { type: 'application/binary' });
var fileURL = URL.createObjectURL(file);
$('#getexcel').show();
var link = document.createElement('a');
link.href = fileURL;
link.download = "myfile.xlsx";
link.click();
URL.revokeObjectURL(file);
}
}, function (error) {
return error;
})
},
using this wave I am getting like this data in excel =>
I want like this data in excel file =>
I've tried your first code and I've found no errors, the resulting xlsx is perfect.
Peheraps I've found the problem: var Array is declared outside the app.get callback... Are you sure that your var Array can be correctly reached by XLSX.utils.json_to_sheet? it's in the same scope? or it's declared somewhere inaccessible?
try to declare it inside the callback and probably all will work well, and, if this is the case, you can use a class or a method to retrieve the var from outside ("how" depends on your code)
P.s. change the name of the var, is not a good habit overwrite the Array object ;)