日期:2014-05-17 浏览次数:20453 次
public static void TableToExcel(DataTable dt, string fileName, bool saveFile, Encoding ecoding = null)
{
StringWriter stringWriter = new StringWriter();
#region 设置数字为文本形式,避免长数字转为科学计数法而丢失0
string strStyle = "<style>td{mso-number-format:'\\@';}</style>";
stringWriter.WriteLine(strStyle);
#endregion
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid excel = new DataGrid();
TableItemStyle AlternatingStyle = new TableItemStyle();
TableItemStyle headerStyle = new TableItemStyle();
TableItemStyle itemStyle = new TableItemStyle();
headerStyle.Font.Bold = true;
headerStyle.HorizontalAlign = HorizontalAlign.Center;
itemStyle.HorizontalAlign = HorizontalAlign.Left;
excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
excel.HeaderStyle.MergeWith(headerStyle);
excel.ItemStyle.MergeWith(itemStyle);
excel.GridLines = GridLines.Both;
excel.HeaderStyle.Font.Bold = true;
excel.DataSource = dt.DefaultView;
excel.DataBind();
excel.RenderControl(htmlWriter);
int fileN = fileName.LastIndexOf('\\');
string tmpName = fileName.Substring(fileN + 1);
// 文件的保存路径