0

Sending it is easy enough so please don't take this as a duplicate question... I saw one to do with perl...

So here's what I've got:

var data = GetSqlData();
var dataGrid = new GridView { DataSource = data };
dataGrid.DataBind();

var sw = new StringWriter();
var htw = new HtmlTextWriter(sw);
dataGrid.RenderControl(htw);
var dataString = sw.ToString();

using (var ms = new MemoryStream(Encoding.ASCII.GetBytes(dataString)))
{
    var attachment = new Attachment(ms, fileName + ".xlsx", "application/ms-excel");
    var disposition = attachment.ContentDisposition;
    disposition.CreationDate = DateTime.Now;
    disposition.ModificationDate = DateTime.Now;
    disposition.ReadDate = DateTime.Now;
    disposition.FileName = fileName + ".xlsx";
    disposition.Size = ms.Length;
    disposition.DispositionType = DispositionTypeNames.Attachment;

    mail.Attachments.Add(attachment);

    SendMail(mail);
}

I do this for direct downloads for my website (slightly differently - along the lines of this answer). What I'm struggling to get around is the fact that the content I'm writing to the file that's being attached is the raw html so it's not readable in Excel...

Anyone know how to correct this? I mean I can write just the data comma delimited row for row, but since I have all this code written, I'd rather avoid changing too much if I can.

Thanks in advance.

Ortund
  • 8,095
  • 18
  • 71
  • 139
  • You create your attachment with an xlsx ending. Even when writing comma delimited rows, what you get is a csv file, but not an Excel document. xlsx is a binary, zipped format. So you have to look for an html2xlsx converter oder create the xlsx manually. You can use the OpenXML SDK for that. – Stefan Illner Dec 11 '18 at 15:25
  • What is raw html? Httml has special characters so you must use Convert.ToBase64String(byte[] Array); and put into body of html. I guess this is waht Stefan is referring to as binary zipped. On the receiving end you must unzip file using Convert.FromBase64String(string data); – jdweng Dec 11 '18 at 15:31

0 Answers0