使用using System.IO;
///
/// 导出Excel文件,并自定义文件名
///
public static void DataTableExcel(System.Data.DataTable dtData, String FileName)
{
GridView dgExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application nd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "GB2312";
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
dgExport = new GridView();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
}
ToDataTableClass类
public static class ToDataTableClass
{
///
/// Convert a List{T} to a DataTable.
///
public static DataTable ToDataTable(List items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
///
/// Determine of specified type is nullable
///
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
///
/// Return underlying type if type is Nullable otherwise return the type
///
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}
}
controller:
public ActionResult GetData(string keyValue,string filename)
{
System.Data.DataTable __dtData = _userExamApp.GetData(keyValue);
ExcelHelper.DataTable3Excel(__dtData, filename + "的试卷记录");
}
app:
public DataTable GetData(string keyValue)
{
DataTable __mydt = ToDataTableClass.ToDataTable(Get(keyValue));
__mydt.Columns.Remove("A1");
__mydt.Columns.Remove("A2");
__mydt.Columns["A3"].ColumnName = "A3Name";
__mydt.Columns["A4"].ColumnName = "A4Name"; 9
return __mydt;
}
我会经常修改 不希望被转载!