使用javascript函数在mvc5中读取Excel文件

时间:2016-02-09 10:02:37

标签: jquery-file-upload ajaxform asp.net-mvc-ajax asp.net-mvc-file-upload

Excel工作表想要在MVC5中点击按钮上传时读取。上传的excel文件名使用AJAX方法传递给操作。这里的文件变量在post方法中获取null值。 这里如何在下面的ajax方法中将所选文件作为HttpPostedFileBase传递。  `

 <input style="display:none" type="file" id="fileupload1" />
     <button type="button"  onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button>
    <span style="display:none" id="spnName"></span>



$(function () {$("#fileupload1").change(function () {
    $("#spnName").html($("#fileupload1").val().substring($("#fileupload1").val().lastIndexOf('\\') + 1));


    var file = $("#spnName").html();
              $.ajax({
        url: "UploadExcelForContractStaff",
        type: 'POST',
        data: JSON.stringify({ file: file }),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data) {

        }
    });


});
});`



  [AcceptVerbs(HttpVerbs.Post)]
    public string UploadExcelForContractStaff(HttpPostedFileBase uploadFile)
    {
        StringBuilder strValidations = new StringBuilder(string.Empty);
        try
        {
            if (uploadFile.ContentLength > 0)
            {
                string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
               Path.GetFileName(uploadFile.FileName));
                uploadFile.SaveAs(filePath);
                DataSet ds = new DataSet();

                //A 32-bit provider which enables the use of

                string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";

                using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
                {
                    conn.Open();
                    using (DataTable dtExcelSchema = conn.GetSchema("Tables"))
                    {
                        string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                        string query = "SELECT * FROM [" + sheetName + "]";
                        OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
                        //DataSet ds = new DataSet();
                        adapter.Fill(ds, "Items");
                        if (ds.Tables.Count > 0)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                                {
                                    //Now we can insert this data to database...
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex) { }
        return "";
    }

1 个答案:

答案 0 :(得分:0)

我得到了解决方案。改变了代码,如

if (cursor != null) { int columnCount = cursor.getColumnCount(); for (int i=0; i < columnCount; i++) { android.util.Log.e(TAG,"Column [" + i + "]: " + cursor.getColumnName(i)); } }

<form enctype="multipart/form-data" id="frmUplaodFileAdd"> @Html.AntiForgeryToken() <input style="display:none" type="file" id="fileupload1" /> <button type="button" onclick='$("#fileupload1").click()'>UPLOAD FROM EXCEL</button> <span style="display:none" id="spnName"></span> </form>

$.ajax({ url: "UploadFile", //Server script to process data type: 'POST', async: false, xhr: function () { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Check if upload property exists myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload } return myXhr; }, data: formData, //Options to tell jQuery not to process data or worry about content-type. cache: false, contentType: false, processData: false, success: function (data) { } });