1

I need to read an excel file sended to the controller via ajax (format httppostfilebase) and get their data The file gonna be uploaded from a website and need to not be saved on disk. I got this on PageWeb (The button to select the file and the one who make the upload ("Analizar"):

<input type="file" accept=".xls,.xlsx" id="cargarArchivo" class="cargarArchivo"/>
    <br/>
 <input type="button" class="analizarArchivo" value="Analizar" onclick="AnalizarArchivoEmpleados()"/>

This on JS (The one who send the file, on format "HttpPostFileBase" (the rest is just validation and that):

var mensajeDialogo;
function AnalizarArchivoEmpleados () {
var nombreArchivo = $(".cargarArchivo").val();
//Se verifica que hay un archivo seleccionado y que su extension sea Excel (xls, xlsx)
if ($(".cargarArchivo").get(0).files.length == 0 || nombreArchivo.indexOf(".xls") == -1) {
    mensajeDialogo = "Porfavor seleccione un archivo";
    if ($(".cargarArchivo").get(0).files.length != 0 && nombreArchivo.indexOf(".xls") == -1) {
        mensajeDialogo = mensajeDialogo + "<br> con extencion valida Excel (xls, xlsx)";
    }
    $('<div>' + mensajeDialogo + "</div>").dialog({
        scriptCharset: "utf-8",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        draggable: false,
        modal: true,
        resizable: false,
        width: 'auto',
        title: 'Analizar Archivo',
        buttons: {
            "Aceptar": function () {
                $(this).dialog("close");
            }
        }
    }); 
} else {
    //Se verifica que el navegador soporte windows.FormData , para el envio de archivo excel
    if (window.FormData !== undefined) {
        alert("si lo soporte oe");
        var archivoExcelData = new FormData();
        var totalFiles = document.getElementById("cargarArchivo").files.length;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("cargarArchivo").files[i];

            archivoExcelData.append("cargarArchivo", file);
        }
        $.ajax({
            type: 'POST',
            url: "/Empleados/AnalisisArchivoExcel",
            data: archivoExcelData ,
            dataType: 'json',
            contentType: false,
            processData: false,
            statusCode: {
                401: function () {
                    MostrarMensajeSinPermiso();
                },
                200: function (data, status, xhr) {
                    var expirado = xhr.getResponseHeader('Expires');
                    if (expirado == "-1") {
                        MostrarMensajeSessionExpirada();
                    } else {
                        alert("volvi");
                    }
                }
            }
        });
    }else {
        mensajeDialogo = "Su navegador no soporta envio de archivos <br>Porfavor actualize su navegador";
        $('<div>' + mensajeDialogo + "</div>").dialog({
            scriptCharset: "utf-8",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            draggable: false,
            modal: true,
            resizable: false,
            width: 'auto',
            title: 'Error',
            buttons: {
                "Aceptar": function () {
                    $(this).dialog("close");
                }
            }
        });    
    }
}};

And this on the Controller:

 [HttpPost]
 public void AnalisisArchivoExcel()
 {
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        var fileName = Path.GetFileName(file.FileName);            
        string fileContentType = file.ContentType;
        byte[] fileBytes = new byte[file.ContentLength];
        var data = file.InputStream.Read(fileBytes, 0, 
        Convert.ToInt32(file.ContentLength));
   }
}

the "data" var, just show numbers and nothing else, i need to read that file a get the data

Gonzalox2
  • 21
  • 6
  • If you're interested in reading the excel part, check out NPOI: https://github.com/tonyqus/npoi . You can find a few tutorials and examples on the internet: https://stackoverflow.com/questions/5855813/how-to-read-file-using-npoi. You can feed it a byte stream directly so no need to save the file on disk. You can get it from NuGet and it's free! – Ted Chirvasiu Sep 04 '18 at 17:33

1 Answers1

0

If you want to read the Excel document and its cells, and you happen to have SQL Server installed with OLEDB enabled, you can read the excel document directly and convert it into a DataTable

Such as this question: Reading excel file using OLEDB Data Provider

Note how it can handle both xls and xlsx files by changing the provider type

EDIT: I remembered a project i did this in before and found it, so heres all the code you need

            DataTable dt = new DataTable();

            string connStr = "";
            if (fileExtension == ".xls")
            {
                connStr = string.Format(String.Format("provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';Extended Properties='Excel 8.0;IMEX=1;';", FullFilePath), FullFilePath, true);
            }
            else
            {
                connStr = string.Format(String.Format("provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}';Extended Properties='Excel 12.0;IMEX=1;';", FullFilePath), FullFilePath, true);
            }

            using (OleDbConnection dbConn = new OleDbConnection(connStr))
            {
                if (System.IO.File.Exists(FullFilePath))
                {
                    dbConn.Open();
                    DataTable dtSchema = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    OleDbCommand dbCmd = new OleDbCommand(String.Format("SELECT * FROM [{0}]", dtSchema.Rows[0]["TABLE_NAME"]), dbConn);
                    OleDbDataAdapter dbAdp = new OleDbDataAdapter(dbCmd);

                    try
                    {
                        dbAdp.Fill(dt);
                    }
                }
            }

Where FullFilePath is the correct path to your xls/x file

Tom Baker
  • 61
  • 1
  • 9
  • i dont have it, and the file gonna be uploaded from a website and need to not be saved on disk. I forgot to add that. Thanks anyway – Gonzalox2 Sep 04 '18 at 17:27