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

100分征集解决方案
功能描述:一个DataSet里,数据有上几十万条;现需要对这里面的数据进行导出,导出文件是为.xls的。因此,我有这么一个方法叫GenerateExcel(ds),
public   string   GenerateExcel(DataSet   ds)
{
DataTable   dt   =   ds.Tables[0];
                  StringBuilder   strContent   =   new   StringBuilder();
for(int   i   =   0   ;   i   <   dt.Rows.Count;   i++)
{  

                          //这里面就生成如 <table> <tr> <td> 数据 </td> </tr> </table> 格式的数据
                          strContent.Append(...)
                    }              
                  return   strContent.ToString();
}

得到GenerateExcel方法返回的字符串后,我又将其转成Byte[],再用FileStream.Write方法,写成一个文件.
        现在出现的问题是:在执行GenerateExcel方法时,也就是将DataSet写到文件的过程中,相当的耗内存,以至于将32位操作系统所允许的最大内存使用量都用光了(注:32位操作系统允许使用的内存上限是3G),最后导致内存溢出的错误。
        现在暂时想到的解决方案,也就是分批次的将数据导入。但我不知还有没有更好的解决方案,故开此贴,征集一下各位兄弟们的宝贵建议。

------解决方案--------------------
sqlserver吗?用bcp直接导出
------解决方案--------------------
填充到数据显示控件然后用Excel类里面的导出,如果不需要在线导出的话可以直接使用SqlServer的导入导出功能,虽然还是慢不过不会导致内存溢出。
------解决方案--------------------
用 XML + XSLT + 客户端EXCEL接口直接实现

xml : ds.GetXml()
xsl : <xsl:template match= "NewDataSet ">
接口:
Response.AppendHeader( "Content-Disposition ", "attachment;filename= " + fileName + ".xls ");
Response.ContentType = "application/ms-excel ";
Response.ContentEncoding=System.Text.Encoding.GetEncoding( "GB2312 ");

------解决方案--------------------
推荐一个好方法,将你的ds转换为datatable即可
public static void DataTableToExcel(HttpResponse re, DataTable dt, string filename)
{
re.Clear();
re.ContentType = "application/vnd.ms-excel ";
re.AddHeader( "Content-Disposition ", "attachment; filename= " + System.Web.HttpUtility.UrlEncode(filename,System.Text.Encoding.UTF8)+ ".xls ");
re.Write(ExportHTML(dt));
re.End();
}
private static string ExportHTML(DataTable dt)
{
StringBuilder sb = new StringBuilder( " <table border=1> <thead> <tr> ");
foreach (DataColumn column1 in dt.Columns)
{
sb.Append( " <td> ");
sb.Append(column1.ColumnName);
sb.Append( " </td> ");
}
sb.Append( " </tr> </thead> <tbody> ");
foreach (DataRow row1 in dt.Rows)
{
sb.Append( " <tr> ");
foreach (DataColumn column2 in dt.Columns)
{
sb.Append( " <td> ");
sb.Append(row1[column2].ToString());
sb.Append( " </td> ");
}
sb.Append( " </tr> ");
}
sb.Append( " </tbody> </table> ");
return sb.ToString();
}
------解决方案--------------------
private void ExportExcelFromDataGrid
( string filename , System.Web.UI.WebControls.DataGrid ToExcelGrid )