简体   繁体   中英

How to get the data in excel file (using NPOI)

I made this function to embed the data when sending an email. So I can call this function in the body of the email.

private static string getHTML(DataTable dt)
{
    StringBuilder myBuilder = new StringBuilder();

    myBuilder.AppendLine("see attached for the updated list.");
    myBuilder.AppendLine("");

    myBuilder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
    myBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>");

    myBuilder.Append("<tr align='left' valign='top'>");


    foreach (DataColumn myColumn in dt.Columns)
    {
        myBuilder.Append("<td align='left' valign='top'>");
        myBuilder.Append(myColumn.ColumnName);
        myBuilder.Append("</td>");
    }

    myBuilder.Append("</tr>");

    int a = 1;

    foreach (DataRow myRow in dt.Rows)
    {
        myBuilder.Append("<tr align='left' valign='top'>");

        foreach (DataColumn myColumn in dt.Columns)
        {
            myBuilder.Append("<td align='left' valign='top'>");
            myBuilder.Append(myRow[myColumn.ColumnName].ToString());
            myBuilder.Append("</td>");
        }

        myBuilder.Append("</tr>");
        a++;

        if (a > 4)
            break;
    }

    myBuilder.Append("</table>");

    return myBuilder.ToString();
}

But when I try to embed the excel file made with NPOI library (instead of Datatable), I can't find the appropriate function or anything to get the data in file.

How can I embed the sheet1 data in the email?

This is the code that I create sheet:

private void Email()
{
    //get the data from database
    DataTable data = GetData();
    IWorkbook workbook;
    workbook = new HSSFWorkbook();

    ISheet sheet1 = workbook.CreateSheet("Sheet 1");

    // [...]
}

And this is the code of sending an email:

private void email()
{
    // [...]        

    using (var ms = new MemoryStream())
    {
        workbook.Write(ms);
        ms.Position = 0;

        using (MailMessage mm = new MailMessage())
        {
            mm.From = new MailAddress("abcd@gmail.com");
            mm.Bcc.Add("abcd@gmail.com");

            SmtpClient smtp = new SmtpClient();
            mm.Subject = "Task List";

            StringBuilder sb = new StringBuilder();
            mm.Body = getHTML(data);
            mm.Attachments.Add(new Attachment(ms, "Task.xls", "application/vnd.ms-excel"));
            mm.IsBodyHtml = true;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
            credentials.UserName = "abc@gmail.com";
            credentials.Password = "1234";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = credentials;
            smtp.Port = 587;
            smtp.Send(mm);
        }
    }
}

workbook.RemoveSheetAt(0);
}

@Ana Carolina Manzan was pretty close to deliver a working solution. You have to convert the Excel workbook to HTML in order to embed the data in an email.

What I've done:

  • Create a workbook with some data and style: CreateWorkbook
  • Convert the workbook to HTML: ConvertExcelToHTML
  • Get an HTML table with a tag {excel} to display the embedded workbook at a specific place: GetHTML
  • Send the mail replacing {excel} with the HTML workbook.

References:


Please try the following working code (tested):

Usings:

using NPOI.HSSF.UserModel;
using NPOI.SS.Converter;
using System.IO;
using System.Net;
using System.Net.Mail;

Main code:

HSSFWorkbook workbook = CreateWorkbook();

string excelEmbedded = string.Empty;

using (MemoryStream ms = new MemoryStream())
{
    workbook.Write(ms);
    ms.Position = 0;

    excelEmbedded = ConvertExcelToHTML(workbook);
}

using (MailMessage message = new MailMessage())
{
    message.Body = GetHTML().Replace("{excel}", excelEmbedded);
    message.Subject = "Embedded Excel";
    message.From = new MailAddress("abcd@gmail.com");
    message.To.Add("abc@gmail.com");
    message.IsBodyHtml = true;

    using (SmtpClient client = new SmtpClient())
    {
        NetworkCredential credentials = new NetworkCredential();
        credentials.UserName = "abc@gmail.com";
        credentials.Password = "1234";

        client.Host = "smtp.gmail.com";
        client.UseDefaultCredentials = true;
        client.Credentials = credentials;
        client.Port = 587;

        client.Send(message);
    }
}

Methods

private HSSFWorkbook createWorkbook()
{
    HSSFWorkbook workbook = new HSSFWorkbook();

    HSSFSheet sheet1 = (HSSFSheet)workbook.CreateSheet("Sheet 1");

    HSSFCellStyle style1 = (HSSFCellStyle)workbook.CreateCellStyle();
    style1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
    style1.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
    style1.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
    style1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;

    HSSFRow row1 = (HSSFRow)sheet1.CreateRow(0);

    HSSFCell cell1 = (HSSFCell)row1.CreateCell(0);
    cell1.SetCellValue("Header 1");
    cell1.CellStyle = style1;

    HSSFCell cell2 = (HSSFCell)row1.CreateCell(1);
    cell2.SetCellValue("Header 2");
    cell2.CellStyle = style1;

    HSSFCell cell3 = (HSSFCell)row1.CreateCell(2);
    cell3.SetCellValue("Header 3");
    cell3.CellStyle = style1;

    HSSFRow row2 = (HSSFRow)sheet1.CreateRow(1);
    row2.CreateCell(0).SetCellValue("Data 1");
    row2.CreateCell(1).SetCellValue("Data 2");
    row2.CreateCell(2).SetCellValue("Data 3");

    return workbook;
}

private string ConvertExcelToHTML(HSSFWorkbook workbook)
{
    ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter();

    // Set output parameter
    excelToHtmlConverter.OutputColumnHeaders = false;
    excelToHtmlConverter.OutputHiddenColumns = false;
    excelToHtmlConverter.OutputHiddenRows = true;
    excelToHtmlConverter.OutputLeadingSpacesAsNonBreaking = false;
    excelToHtmlConverter.OutputRowNumbers = true;
    excelToHtmlConverter.UseDivsToSpan = true;

    // Process the Excel file
    excelToHtmlConverter.ProcessWorkbook(workbook);

    // Return the HTML
    return excelToHtmlConverter.Document.InnerXml;
}

private string GetHTML()
{
    StringBuilder myBuilder = new StringBuilder();

    myBuilder.AppendLine("see attached for the updated list.");
    myBuilder.AppendLine("");

    myBuilder.AppendLine("<table style='border:1px solid black'>");
    myBuilder.AppendLine("<tr><td>Cell Text</td></tr>");
    myBuilder.AppendLine("<tr><td>{excel}</td></tr>");
    myBuilder.AppendLine("</table>");

    return myBuilder.ToString();
}

I think that your best option would be to convert your WorkBook object to html. You can see the results expect of the conversion in this article . You can convert the content of the WorkBook and embed it to the e-mail message like this:

private string ConvertXlsToHtml(IWorkbook workbook)
{
    ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter();

    // Set output parameters 
    excelToHtmlConverter.OutputColumnHeaders = false;
    excelToHtmlConverter.OutputHiddenColumns = true;
    excelToHtmlConverter.OutputHiddenRows = true;
    excelToHtmlConverter.OutputLeadingSpacesAsNonBreaking = false;
    excelToHtmlConverter.OutputRowNumbers = true;
    excelToHtmlConverter.UseDivsToSpan = true;

    // Process the Excel file 
    excelToHtmlConverter.ProcessWorkbook(workbook);

    return excelToHtmlConverter.Document.ToString();
}

....

using (var ms = new MemoryStream())
{
    workbook.Write(ms);
    ms.Position = 0;

    string mailBody = getHTML(data) + ConvertXlsToHtml(workbook);

    using (MailMessage mm = new MailMessage())
    {
        mm.From = new MailAddress("abcd@gmail.com");

        mm.Bcc.Add("abcd@gmail.com");

        SmtpClient smtp = new SmtpClient();
        mm.Subject = "Task List";

        StringBuilder sb = new StringBuilder();
        mm.Body = mailBody;
        mm.Attachments.Add(new Attachment(ms, "Task.xls", "application/vnd.ms-excel"));
        mm.IsBodyHtml = true;
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
        credentials.UserName = "abc@gmail.com";
        credentials.Password = "1234";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = credentials;
        smtp.Port = 587;
        smtp.Send(mm);

    }
}

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