Upload and retrieve an excel file with react and netcore

Lucio Flores
2021-04-16T21:31:39Z

Home.js

| import React from 'react';
|
| class Home extends React.Component {
|
| constructor(props) {
| super(props)
| this.state = {
| file: null
| }
| this.sendFile = this.sendFile.bind(this)
| }
|
| sendFile(event) {
| event.preventDefault();
| //console.log(this.state);
| let formData = new FormData();
| formData.append('file', this.state.file);
|
| fetch('/api/uploadFile/excel', {
| method: 'POST',
| body: formData
| })
| .then(response => response.blob())
| .then(blob => {
| let url = window.URL.createObjectURL(blob);
| let a = document.createElement('a');
| a.href = url;
| a.download = "filename.xlsx";
| document.body.appendChild(a); // for firefox
| a.click();
| a.remove(); //remove element once used
| })
| .catch(error => {
| console.error(error)
| })
| }
|
| render() {
| return (
|
| Hello, world!
|
| this.setState({ file: e.target.files[0] })} />
| Send
|
|
| );
| }
| }
|
| export default Home;

UploadFileController.cs

| using System;
| using System.Collections.Generic;
| using System.IO;
| using System.Linq;
| using System.Threading.Tasks;
| using DocumentFormat.OpenXml;
| using DocumentFormat.OpenXml.Packaging;
| using DocumentFormat.OpenXml.Spreadsheet;
| using Microsoft.AspNetCore.Http;
| using Microsoft.AspNetCore.Mvc;
|
| namespace ExcelUploadAndReturnExample.Controllers
| {
| [Route("api/[controller]")]
| [ApiController]
| public class UploadFileController : ControllerBase
| {
|
| [Route("excel")]
| [HttpPost]
| public IActionResult UploadExcelFile(IFormFile file)
| {
| //validate content type
| //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
|
| if(file.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
| {
| return BadRequest();
| }
|
| List objList = new List ();
|
| Stream fileStream = file.OpenReadStream();
| fileStream.Position = 0;
| using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileStream, false))
| {
| var workbookPart = document.WorkbookPart;
| var workbook = workbookPart.Workbook;
|
| var sheets = workbook.Descendants<Sheet>();
| foreach (var sheet in sheets)
| {
| var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
| var sharedStringPart = workbookPart.SharedStringTablePart;
| var values = sharedStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
|
|
| var rows = worksheetPart.Worksheet.Descendants<Row>();
|
| foreach(var row in rows)
| {
| var cellsInRow = row.Descendants<Cell>();
| var cells = "";
| foreach (var cell in cellsInRow)
| {
| Console.WriteLine(cell.CellReference);
| // The cells contains a string input that is not a formula
| if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
| {
| var index = int.Parse(cell.CellValue.Text);
| var value = values[index].InnerText;
| cells += value + ",";
| }
| else
| {
| cells += cell.CellValue.Text + ",";
| }
|
| if (cell.CellFormula != null)
| {
| cells += cell.CellFormula.Text + ",";
| }
| }
|
| objList.Add(cells);
| }
| }
| }
| fileStream.Position = 0;
| return File(fileStream, "application/octet-stream");
| }
| }
| }