本文实例讲述了asp.net实现导出DataTable数据到Word或者Excel的方法。分享给大家供大家参考,具体如下:
/// < xmlnamespace prefix ="o" ns ="urn:schemas-microsoft-com:office:office" />
/// 导出DataTable数据到Word或者Excel
///
/// Page指令
/// DataTable数据表
/// 导出Word或者Excel表格的名字
/// 导出Word或者Excel表格中内容的标题
/// 导出Word或者Excel的人
/// 导出类型(w:Word,e:Excel)
public bool DataTableToExcel(Page pPage, DataTable dt, string str_ExportTitle, string str_ExportContentTitle, string str_ExportMan, string str_ExportType)
{
bool bl_Result = false;
string str_ExportTypeName = "word";//导出类型
string str_ExportFormat = ".doc";//导出类型的格式
if (str_ExportType.Equals("e"))
{
str_ExportTypeName = "excel";
str_ExportFormat = ".xls";
}
HttpResponse response = pPage.Response;
if (dt.Rows.Count > 0)
{
response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
response.ContentType = "application/ms-" + str_ExportTypeName;
response.AppendHeader("Content-Disposition", "attachment;filename="
+ HttpUtility.UrlEncode(str_ExportTitle, System.Text.Encoding.UTF8).ToString() //该段需加,否则会出现中文乱码
+ str_ExportFormat);
//获取DataTable的总列数
int i_ColumnCount = dt.Columns.Count;
//定义变量存储DataTable内容
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append("
\n");builder.Append("\n");
builder.Append("\n");
builder.Append("\n");
builder.Append("
if (!string.IsNullOrEmpty(str_ExportContentTitle))
{
builder.Append(string.Concat(new object[] { "
",str_ExportContentTitle,
"
" }));}
builder.Append("
");builder.Append("导出人:【" + str_ExportMan + "】,导出时间:【" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "】
");builder.Append("
\n");builder.Append("
序号\n");for (int i = 0; i < i_ColumnCount; i++)
{
if (dt.Columns[i].Caption.ToString().ToLower() != "id")
{
builder.Append("
" + dt.Columns[i].Caption.ToString() + "\n");}
}
#region 此处没有在导出的数据列的最前面加一列(序号列)
//此处没有在导出的数据列的最前面加一列(序号列)
//foreach (DataRow row in dt.Rows)
//{
// builder.Append("
");// for (int j = 0; j < i_ColumnCount; j++)
// {
// if (dt.Columns[j].Caption.ToString().ToLower() != "id")
// {
// builder.Append("
" + row[j].ToString() + "");// }
// }
// builder.Append("
\n");//}
#endregion
#region 在导出的数据列的最前面加了一序号列(注意:非DataTable数据的序号)
//在导出的数据列的最前面加了一序号列(注意:非DataTable数据的序号)
for (int m = 0; m < dt.Rows.Count; m++)
{
builder.Append("
");for (int j = 0; j < i_ColumnCount; j++)
{
if (dt.Columns[j].Caption.ToString().ToLower() != "id")
{
if (j == 0)
{
builder.Append("
" + (m + 1) + "");}
if (j > 0)
{
builder.Append("
" + dt.Rows[m][j - 1].ToString() + "");}
if (j == dt.Columns.Count - 1)
{
builder.Append("
" + dt.Rows[m][j].ToString() + "");}
}
}
builder.Append("
\n");}
#endregion
builder.Append("
");builder.Append("合计:共【" + dt.Rows.Count + "】条记录
");builder.Append("
\n");builder.Append("
");response.Write(builder.ToString());
response.End();
bl_Result = true;
}
return bl_Result;
}
希望本文所述对大家asp.net程序设计有所帮助。