Friday, October 28, 2016

How to force HTML table cell as text in Excel

<td> style to force the cell as text: mso-number-format:"\@";
<td> style to force the cell as number: mso-number-format:General;

Code Behind(cs) file
        public PartialViewResult ExcelFile()
        {
            StringBuilder table = new StringBuilder();
            table.AppendLine("<table>");
            table.AppendLine("<thead>");
            table.AppendLine("<tr>");
            table.AppendLine("<th>Date</th>");
            table.AppendLine("<th>Store</th>");
            table.AppendLine("</tr>");
            table.AppendLine("</thead>");

            table.AppendLine("<tbody>");
            table.AppendLine("<tr>");
            table.Append("<td>10/27/2016</td>");
            table.Append("<td style='mso-number-format:\"\\@\"'>0001</td>");
            table.AppendLine("</tr>");
            table.AppendLine("<tr>");
            table.Append("<td>10/27/2016</td>");
            table.Append("<td style='mso-number-format:\"\\@\"'>0002</td>");
            table.AppendLine("</tr>");
            table.AppendLine("</tbody>");
            table.AppendLine("</table>");

            Response.ContentType = "application/force-download";
            Response.AddHeader("content-disposition", "attachment; filename=ExcelFile_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls");
            Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
            Response.Write("<head>");
            Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
            Response.Write("<!--[if gte mso 9]><xml>");
            Response.Write("<x:ExcelWorkbook>");
            Response.Write("<x:ExcelWorksheets>");
            Response.Write("<x:ExcelWorksheet>");
            Response.Write("<x:Name>ExcelFile</x:Name>");
            Response.Write("<x:WorksheetOptions>");
            Response.Write("<x:Print>");
            Response.Write("<x:ValidPrinterInfo/>");
            Response.Write("</x:Print>");
            Response.Write("</x:WorksheetOptions>");
            Response.Write("</x:ExcelWorksheet>");
            Response.Write("</x:ExcelWorksheets>");
            Response.Write("</x:ExcelWorkbook>");
            Response.Write("</xml>");
            Response.Write("<![endif]--> ");
            Response.Write("</head>");
            Response.Write(table.ToString());
            Response.Flush();

            return PartialView();
        }