如何使用JQuery Ajax创建Excel文件?

时间:2019-04-02 15:15:15

标签: c# jquery json excel asp.net-mvc

我正在使用ExcelLibrary创建一个Excel文件,如果我通常使用ActionResult可以正常工作。问题是我想通过Ajax发送一些参数,它创建并下载文件,但是我不知道该怎么做。

我该怎么办?

创建Excel文件的JsonResult

public JsonResult createExcelFile(String dados){
            try{

                List<SimulacaoPrevisaoModel> json = JsonConvert.DeserializeObject<List<SimulacaoPrevisaoModel>>(dados);

                DataSet ds = new DataSet("New_DataSet");

                DataTable dt = new DataTable("Teste1");
                dt.Columns.Add("Dia");
                dt.Columns.Add("Data");
                dt.Columns.Add("Aporte($)");
                dt.Columns.Add("Meta(%)");
                dt.Columns.Add("Meta($)");
                dt.Columns.Add("Lucro($)");

                int index = 1;
                foreach (SimulacaoPrevisaoModel x in json)
                {
                    dt.Rows.Add(index, x.data, x.aporte, x.porcentagem, x.metaReal, x.lucro);
                    index++;
                }               

                ds.Tables.Add(dt);

                MemoryStream stream = new MemoryStream();
                ExcelLibrary.DataSetHelper.CreateWorkbook(stream, ds);

                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("content-disposition", string.Format("attachment;filename=Simulação_{0}.xls", DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")));

                stream.WriteTo(Response.OutputStream);

                Response.End();

                jsonResposta.Add("status", "1");
                jsonResposta.Add("msg", "Arquivo XLS gerado com sucesso!");

            }catch(Exception e) {
                jsonResposta.Add("status", "0");
                jsonResposta.Add("msg", "Erro gerando XLS: " + e.Message);
                Debug.WriteLine("Erro gerando XLS: " + e.Message);
            }

            return Json(jsonResposta);
        }

Ajax

//create a xls file
function createXLS() {    

    var loading = $("#div_loading");
    $(document).ajaxStart(function () {
        loading.show();
    });
    $(document).ajaxStop(function () {
        loading.hide();
    });

    $.ajax({
        accepts: { json: 'application/json' },
        dataType: 'json',
        type: "POST",
        url: "/Trade/createExcelFile",
        data: { 'dados[]' : JSON.stringify(lista) },
        success: function (data) {
            var status = data["status"];
            var msg = data["msg"];
            if (status === "1") {               
                $("#errorMessage").html(msg);
                $("#errorMessage").prop("class", "alert alert-success");               
            } else {
                $("#errorMessage").html(msg);
                $("#errorMessage").prop("class", "alert alert-danger");
            }
            $("#errorMessage").show()
            window.scrollTo(0, 0);
        },
        error: function (xhr, status) {
            $("#errorMessage").html("Erro");
            $("#errorMessage").prop("class", "alert alert-danger");
            $("#errorMessage").show()
        }
    });
}

0 个答案:

没有答案