日期:2014-05-18  浏览次数:21009 次

急!急!GridView是代码分页的,要全部导出EXCEL,而不是gridview第一页
请教各位高手:

  GridView是代码分页的,要全部导出EXCEL,而不是gridview第一页

  GridView1.AllowPaging = False不能用,因为我是代码分页的。

------解决方案--------------------
public void DataTableToExcel(System.Web.HttpResponse response, DataSet ds, string strDefaultName)
{
const string EXTEND_XLS = "xls";
const string EXTEND_CSV = "csv";
try
{
if (null == ds || ds.Tables.Count< 1)
{
return;
}
if (null == strDefaultName || strDefaultName.Trim().Length < 1)
{
throw new ArgumentException("导出的默认文件名不可为空!");
}
int iDocPos = strDefaultName.LastIndexOf('.');

if (iDocPos <= 0)
{
throw new ArgumentException("导出的默认文件名不正确!");
}

iDocPos++;

//取得扩展名
string strExtenName = strDefaultName.Substring(iDocPos, strDefaultName.Length - iDocPos);

if (strExtenName.Trim().ToLower() != EXTEND_XLS && strExtenName.Trim().ToLower() != EXTEND_CSV)
{
throw new ArgumentException("导出的默认文件的扩展名不正确!");
}

//导出的文件的分隔符
string strSplitChar = string.Empty;

if (strExtenName.Trim().ToLower() == EXTEND_XLS)
{
strSplitChar = "\t";

}
else if (strExtenName.Trim().ToLower() == EXTEND_CSV)
{
strSplitChar = ",";
}
string data = "";
System.IO.StringWriter sw = new System.IO.StringWriter();
string strTemp = string.Empty;
foreach(DataTable dt in ds.Tables)
{


//输出头
foreach (DataColumn column in dt.Columns)
{
strTemp += column.ColumnName + ",";
}

//for (int i = 0; i < dt.Columns.Count; i++)
//{
// if (i != dt.Columns.Count - 1)
// {
// strTemp += dt.Columns[i].ColumnName + strSplitChar;
// }
// else
// {
// strTemp += dt.Columns[i].ColumnName;
// }
//}
sw.WriteLine(strTemp);

strTemp = "";
//输出内容
for (int ii = 0; ii < dt.Rows.Count; ii++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j != dt.Columns.Count - 1)
{
strTemp += dt.Rows[ii][j].ToString() + strSplitChar;
}
else
{
strTemp += dt.Rows[ii][j].ToString();
}
}
sw.WriteLine(strTemp);
strTemp = "";
}
data = "\n\n\n\n";
sw.WriteLine(data);

}
sw.Close();
response.Buffer = false;
response.AppendHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(strDefaultName, System.Text.Encoding.UTF8));
response.Con