Отправка автоматически сгенерированного файла Excel в виде электронного письма в asp. net mvc - PullRequest
0 голосов
/ 05 апреля 2020

Я создаю mvc приложение, используя сущность. У меня есть одна таблица с именем студентов, я sh, чтобы отправить все записи из этой таблицы в формате Excel на адрес электронной почты. Я пробовал следующий код, но он не работает. Я хотел бы помочь, пожалуйста. Я пытался использовать DataTable, потому что я видел его на другом сайте, но я не знаю, как это реализовать.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "StudentID,Name,Age,Address,Email,IsActive")] Student student)
    {



        if (ModelState.IsValid)
        {
            student.IsActive = true;
            db.Students.Add(student);
            db.SaveChanges();
            try
            {

                DataTable tempTable = new DataTable();

                System.IO.MemoryStream str = DataToExcel(db.Students.ToList());
                MailMessage mm = new MailMessage(student.Email, student.Email)
                {
                    Subject = "Student Details for " + student.Name.ToUpper(),
                    IsBodyHtml = true,
                    Body = " Good Day : " + student.Name.ToUpper() + ", Please find attached student information for Student ID : " + student.StudentID
                };


                mm.Attachments.Add(new Attachment(str, "MonthEndSummary.xls"));
                SmtpClient smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    Credentials = new NetworkCredential("enigma2019project@gmail.com", "xxxxx")

                };
                smtp.Send(mm);

                return RedirectToAction("Index");
            }
            catch (Exception e)
            {

                Response.Write(e.Message);
            }

        }

        return View(student);
    }


private MemoryStream DataToExcel(List<Student> list)
    {
        throw new NotImplementedException();
    }

    public System.IO.MemoryStream DataToExcel(DataTable dt)
    {
        //StreamWriter sw = new StreamWriter();
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        if (dt.Rows.Count > 0)
        {

            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();
            dgGrid.HeaderStyle.Font.Bold = true;
            //Get the HTML for the control.
            dgGrid.RenderControl(hw);
            //Write the HTML back to the browser.
            //Response.ContentType = application/vnd.ms-excel;
            Response.ClearContent();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = System.Text.Encoding.Default;

        }
        System.IO.MemoryStream s = new MemoryStream();
        System.Text.Encoding Enc = System.Text.Encoding.Default;
        byte[] mBArray = Enc.GetBytes(tw.ToString());
        s = new MemoryStream(mBArray, false);

        return s;
    }
...