close
若不使用third party原件(如 : NPOI)產生excel檔案
可採用以下方法
參考網址 : http://www.aspforums.net/Threads/916114/Export-HTML-string-to-Excel-with-formatting-in-ASPNet/
效果 :
sampe code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Data; | |
using System.Text; | |
protected void ExportToExcel(object sender, EventArgs e) | |
{ | |
DataTable dt = new DataTable(); | |
dt.Columns.AddRange(new DataColumn[3] { | |
new DataColumn("Id"), | |
new DataColumn("Name"), | |
new DataColumn("Country")}); | |
dt.Rows.Add(1, "John Hammond", "United States"); | |
dt.Rows.Add(2, "Mudassar Khan", "India"); | |
dt.Rows.Add(3, "Suzanne Mathews", "France"); | |
dt.Rows.Add(4, "Robert Schidner", "Russia"); | |
StringBuilder sb = new StringBuilder(); | |
sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>"); | |
sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Order Sheet</b></td></tr>"); | |
sb.Append("<tr><td colspan = '2'></td></tr>"); | |
sb.Append("<tr><td><b>Order No:</b> 100</td><td><b>Date: </b>" + DateTime.Now + " </td></tr>"); | |
sb.Append("<tr><td><b>From :</b> " + "Company Name" + " </td><td><b>To: </b>" + " Some Company " + " </td></tr>"); | |
sb.Append("</table>"); | |
sb.Append("<table border = '1'>"); | |
sb.Append("<tr>"); | |
foreach (DataColumn column in dt.Columns) | |
{ | |
sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>"); | |
sb.Append(column.ColumnName); | |
sb.Append("</th>"); | |
} | |
sb.Append("</tr>"); | |
foreach (DataRow row in dt.Rows) | |
{ | |
sb.Append("<tr>"); | |
foreach (DataColumn column in dt.Columns) | |
{ | |
sb.Append("<td>"); | |
sb.Append(row[column]); | |
sb.Append("</td>"); | |
} | |
sb.Append("</tr>"); | |
} | |
sb.Append("</table>"); | |
Response.Clear(); | |
Response.Buffer = true; | |
Response.AddHeader("content-disposition", "attachment;filename=ReceiptExport.xls"); | |
Response.Charset = ""; | |
Response.ContentType = "application/vnd.ms-excel"; | |
string style = @"<style> .textmode { } </style>"; | |
Response.Write(style); | |
Response.Output.Write(sb.ToString()); | |
Response.Flush(); | |
Response.End(); | |
} |
全站熱搜