简体   繁体   中英

Get excel worksheet from workbook and send it as email attachment

can anyone help me on how can i get the excel worksheet and send it as attachment. The code for email is already good, my only problem is to get the worksheet.

You can use EPPLUS to achieve this pretty straight forward. Here's a code snippet from their documentation on github.

   //Open the workbook (or create it if it doesn't exist)
    var fi=new FileInfo(@"c:\workbooks\myworkbook.xlsx")
    using (var p = new ExcelPackage(fi))
    {
       var ws=p.Workbook.Worksheets["MyWorksheetName"];

       //Save and close the package.
       p.Save();
    }
    public void sendMail()
    {
        Console.WriteLine("Mail sending...");
        MailMessage ePosta = new MailMessage();
        ePosta.From = new MailAddress("From mail adress");
        ePosta.To.Add("To Mail Adress");
        ePosta.CC.Add("CCmail adress (optional)")

        ePosta.Attachments.Add(new Attachment(@"C:/xx/yy/abc.xlsx"));
        ePosta.Subject = "Subject here"
        ePosta.Body = "Body Message here"
        SmtpClient smtp = new SmtpClient();

        smtp.Credentials = new System.Net.NetworkCredential(From mail adress, From mail password);
        smtp.Port = 587;
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        object userState = ePosta;
        try
        {
            smtp.SendAsync(ePosta, (object)ePosta);
        }
        catch
        {
            MessageBox.Show("Mail sending error");
        }
        Console.WriteLine("Mail sent");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM