I am developing an Angular Application in that i am trying to upload an excel file, the excel file contains some text data in column and specifically one column contains an images in its rows like D1, D2, D3 and so on.
i am reading the excel file at my front end but i think it is not reading the image in the respective column on console.log it is giving me only text data in the columns
<form [formGroup]="uploadForm" (ngSubmit)="Excel_Upload()" >
<a id="excel_upload_label">Upload Excel</a>
<input type="file" (change)="onEx_FileChange($event)" multiple="false">
<button type = "submit" id="excel_upload_button">Upload Properties</button>
</form>
onEx_FileChange(evt : any){
const target : DataTransfer = <DataTransfer>(evt.target);
if(target.files.length !== 1){
alert("Multiple File upload");
}
const reader : FileReader = new FileReader();
reader.onload = (e : any) =>{
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
const wsname : string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
this.data = (XLSX.utils.sheet_to_json(ws, {header:1}));
console.log(this.data); // on this console i am getting only text data
};
reader.readAsBinaryString(target.files[0]);
}
Pictures are supported only in paid version of sheetjs.
Related
I am having one html dynamic form one dropdown list of companies. If
user will select any of the company from dropdown it will show
respective employees of particular company in table.With each row of i
am attaching input[file]. Now user will upload payslip of each
employee and save data. my concern is to upload each rows files into
database into different row.
component.html :
<table *ngIf="allemp">
<tr>
<th>ID</th>
<th>Name of Employee</th>
<th>Attached Payslip</th>
</tr>
<tr *ngFor="let data1 of allemp">
<td>{{data1.id}}</td>
<td>{{data1.emp_name}}</td>
<input formArrayName='payslip' type="file" (change)="onFileChangeInfo($event,i)" multiple></td>
</tr>
</table>
function for multiple uplaods in ts file:
onFileChangeInfo(event,index) {
const reader = new FileReader();
var filesAmount = event.target.files.length;
this.items= this.myForm1.controls['payslip'] as FormArray;
console.log(this.items);
if(event.target.files && event.target.files.length > 0) {
const [files] = event.target.files;
this.regInfoName=event.target.files[0].name;
this.urlInfoUploadd= event.target.result;
for (let i = 0; i < filesAmount; i++) {
reader.readAsDataURL(event.target.files[i]);
reader.onload = () => {
this.urlInfoUpload = this.urlInfoUploadd;
this.regInfoNameHtml=this.regInfoName;
this.items.controls[index].patchValue({
'data_blob': reader.result,
'data_file':files.name,
});
console.log(files.name);
this.cd.markForCheck();
};
}
}
}
on console.log(filesAmount) it shows me all selected files. But in database goes only last file.
i dont understand what's wrong in my code. please help me with the same.
I've had a similar experience like this in ReactJS before. Hence, i will try my best to re-write the code I used for you.
You can use Promise.all() to load an array of files asynchronously:
onFileChangeInfo(event) {
const files = Array.from(event.target.files); // Get files in array form
// Map each file to a promise that resolves an array of files
const promises = files.map(file => {
return (new Promise(resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', (ev) => {
resolve(ev.target.result);
}
reader.addEventListener('error', reject);
reader.readAsDataURL(file);
}
});
// Once all promises are resolved, store the file blob in your variable
Promise.all(promises).then(files => {
this.items.controls.patchValue({
'data_blob': files
},
}, error => { console.error(error); });
}
I don't know how your code looks like so i don't know what you're using the "index" parameter for. But if this.items.controls is an array where you want to store each file blob, then you don't need the "index".
I'm new to angular, currently i'm working in a project which needs an csv export. Here i'm using Angular 6 as frontend and laravel as backend
This is how i wrote laravel function using mattwebsite/excel
// Lead export to csv
public function downloadExcel(Request $request)
{
$credentials = $request->only('token');
$token = $credentials['token'];
$userid = $this->getUseridFromToken($token);
$type = "xls";
$data = DB::table('user_mailbox AS A')
->select('A.id', 'A.name', 'A.email', 'A.phone', DB::raw('DATE_FORMAT(A.send_on, "%d / %b / %Y") as send_on'), 'B.listing_heading','B.listing_id','B.listing_heading', 'C.name')
->leftjoin('broker_listing AS B', 'B.listing_id', '=', 'A.listing_id')
->leftjoin('users AS C', 'C.id', '=', 'A.sent_by')
->where('A.sent_to', $userid)
->where('A.user_type', '1')
->orderBy('A.id', 'desc')->get()->toArray();
Excel::create('Lead_Export', function($excel) use ($data) {
$excel->sheet('Lead_Export', function($sheet) use ($data)
{
$sheet->fromArray($data);
});
})->download($type);
}
This is how i wrote function in angular component
// Download leads as excel
download_excel(){
const fd = new FormData();
fd.append('token',this.token);
this.brokerleads.downloadLeads(fd).subscribe(
data => this.handleResponsedwnload(data),
error => this.handleErrordwnload(error)
);
}
handleResponsedwnload(data){ console.log('test');
const blob = new Blob([data], { type: 'text/xls' });
const url= window.URL.createObjectURL(blob);
window.open(url);
}
handleErrordwnload(data){
}
service is like this
// Download as excel
downloadLeads(data):Observable<any>{
return this.http.post(`${this.baseUrl}downloadExcel`, data);
}
view
<a class="export-leads" href="javascript:void(0);" (click)="download_excel()" >EXPORT LEADS</a>
while doing this i'm getting response like this but file is not downloading
You need to navigate the browser to the route where the Excel file is made on the backend (in a new tab) either with a link <a href="path" target="_blank"> or with window.open
The ->download() function sets headers so that the file will be automatically downloaded.
When you fetch this data with an AJAX call (which is what HttpClient does) you simply get the binary data returned (which is what you see in your Response tab in Chrome developer tools).
(There are front-end hacks to download a file retrieved by ajax such as creating a link element and clicking it with JavaScript (see below), but they can not be recommended):
let fileName = 'filename.xlsx';
let a = document.createElement('a');
a.href = window.URL.createObjectUrl(responseData);
a.download = fileName;
a.click();
This can also be done using file-saver:
import * as FileSaver from 'file-saver';
this.http.post(`${this.baseUrl}downloadExcel`, data, { responseType: 'blob' })
.subscribe((resp: any) => {
saveAs(resp, `filename.csv`)
});
This function working for me to export csv,
downloadFile(data: any) {
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(data[0]);
let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
let csvArray = csv.join('\r\n');
var a = document.createElement('a');
var blob = new Blob([csvArray], {type: 'text/csv' }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "myFile.csv";
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
Hello friends I created a project in angular 4 I want to upload an image and sent request to the PHP file but form-data can't append values and images.
please help me
I include FormGroup, FormControl, FormBuilder, Validators, Http
const Image = this.com_Image.nativeElement;
if (Image.files && Image.files[0]) {
this.comImageFile = Image.files[0];
}
const ImageFile: File = this.comImageFile;
// [enter image description here][1]
let formData = new FormData();
formData.append('companyName', value.companyName);
formData.append('username', value.username);
formData.append('uploadFile', ImageFile, ImageFile.name);
console.log(formData);
Html
<input #fileSelect type="file" class="form-control" (change)="onFileChanged($event)" accept=".jpg, .png"/>
component
export class FileUploadComponent {
#ViewChild('fileSelect') fileSelectInput: ElementRef;
fileToUpload: any;
onFileChanged(event) {
// https://stackoverflow.com/questions/13602039/e-srcelement-is-undefined-in-firefox
this.fileToUpload = (event.srcElement || event.target).files;
let formData: FormData = new FormData();
formData.append('file', this.fileToUpload[0]);
this.createOrUpdateResource(formData);
}
// https://stackoverflow.com/questions/48059121/angular4-file-upload-put-request-fails,
so making this POST
private createOrUpdateResource(formData: FormData) {
this.http.post<any>(`http://localhost:8080/upload`, formData).subscribe((res) => {
//success
}, error => {
//error
});
}
}
Have you tried to pass only name and value for the image?
For file management (in general) this has worked for me:
formData.append('uploadFile', ImageFile);
I have a BLOB URL that has the pdf file with the content:
blob:http://localhost/468479b7-7db1-4e35-ab35-acf9ff0739f8
Using the filereader i convert it to base64:
var myReader = new FileReader();
var blob = new Blob([v.src], {type: "application/pdf"});
myReader.readAsDataURL(blob);
myReader.onload = function(event) {
result = event.target.result;
console.log(result);
console.log(v.src);
};
The result is:
data:application/pdf;base64,YmxvYjpodHRwOi8vbG9jYWxob3N0LzQ2ODQ3OWI3LTdkYjEtNGUzNS1hYjM1LWFjZjlmZjA3MzlmOA==
Now can i get the pdf content from the encoded url?
If not, what are my options?
Extract the content part. Decode and save into a file.
$data = explode(';',"data:application/pdf;base64,YmxvYjpodHRwOi8vbG9jYWxob3N0LzQ2ODQ3OWI3LTdkYjEtNGUzNS1hYjM1LWFjZjlmZjA3MzlmOA");
$encoded = explode(',',$data[1]);
file_put_contents("test.pdf",base64_decode($encoded[1]));
Export HighChart as an image in excel file together with the other page contents like tables, text, etc. When I click the export button the whole Page content will be save as excel file via header but instead of exporting all page content to excel file it excludes the HighChart Graph. I think the solution is to export the graph as image in excel but I don't have any idea how to that. Is there anyone know how to do it or have any idea how to solve this problem?
Here is link on highcharts documentation. Thats will help u to export image and store it.
a) Documentation #1
b) Documentation #2
That will help u with PHPExcel classs API.
And finally exapmle of image paste to a sheet, using PHPExcel class: one or two;
Have more questions? See that links: one, two.
And official PHPExcel examples: here.
Good luck!
First you have to send the svgtext and the csv text ti the server via ajax.
Then do the following:
public JsonResult ExportToImage(string base64, string graphdata)
{
try
{
var base64String = base64.Remove(0, 1);
var rows = graphdata.Split('\n');
byte[] bytes = Convert.FromBase64String(base64);
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "Content\\Images\\");
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.xls")
.Where(p => p.Extension == ".xls").ToArray();
foreach (FileInfo file in files)
try
{
file.Attributes = FileAttributes.Normal;
System.IO.File.Delete(file.FullName);
}
catch { }
using (Image image = Image.FromStream(new MemoryStream(bytes)))
{
image.Save(path+"output.png", ImageFormat.Jpeg); // Or Png
}
var xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
for(var y=0; y<rows.Count();y++)
{
var row = rows[y];
var columValues = row.Split(',');
for (var x = 0; x < columValues.Count(); x++)
{
xlWorkSheet.Cells[y+20, x+1] = columValues[x];
}
}
xlWorkSheet.Shapes.AddPicture(path + "output.png", MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, 0, -1, -1);
var fileName = string.Format("GraphDataExport{0}.xls", DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"));
xlWorkBook.SaveAs(path + fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
return Json(fileName);
}
catch (Exception e)
{
return Json(e.Message + Environment.NewLine + e.InnerException + Environment.NewLine + e.Data + Environment.NewLine);
}
}
Now you can do a window.location to that file