同上,谢谢!!!
解决方案 »
- FlyTreeView如何进行数据绑定?
- vs2010页面设计时出现创建控件出错求解决
- 我定义了一个<asp:button id="RegisterButton" runat="server" Text="按钮" onclick="ButtonClick" ></asp:button>,有什么办法让响应这个函数时不调用page_load函数
- 请教各位,sqlServer数据库中有没有一个对一个数进行四舍五入的函数???
- 我封装一个DataGrid导出到Excel得类,但是导出时出错!居然导出得是ASP.NET web页面!请教!
- 长沙的朋友看过来! 公司招 C#,asp.net 程序员。
- 有好人吗?请问如何在Aspx文件中访问用户控件中的TextBox??我只有10分拉 ^_^
- ASP.NET开发的WEB如何保护DLL文件不被人反编译?
- asp.net中模糊查询
- 发布到线上服务器的网站,访问时在域名后面多出一长串字符
- 在线紧急求救!!!水晶报表:工资报表中如何控制工资项(列)的位置。 急求!!!!
- 讨论:关于一个图片存储管理系统!权限问题!
public void Save(System.Web.UI.Control source, DocumentType type)
{
Response.Clear();
Response.Buffer= true; //设置Http的头信息,编码格式
if (type == DocumentType.Excel)
{
//Excel
Response.AppendHeader("Content-Disposition","attachment;filename=result.xls");
Response.ContentType = "application/ms-excel";
}
else if (type == DocumentType.Word)
{
//Word
Response.AppendHeader("Content-Disposition","attachment;filename=result.doc");
Response.ContentType = "application/ms-word";
} //设置编码
Response.Charset="GB2312";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312"); //关闭控件的视图状态
source.EnableViewState =false; //初始化HtmlWriter
System.IO.StringWriter writer = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
source.RenderControl(htmlWriter); //输出
Response.Write(writer.ToString()); Response.End();
}
//以下是保存图片
public void SavePic()
{
string path = Server.MapPath(".") + @"\images\Chart.jpeg";
FileStream file = File.OpenRead(path);
byte[] content = new byte[file.Length];
file.Read(content,0,content.Length);
file.Close(); Response.Clear();
Response.AppendHeader("Content-Disposition","attachment;filename=Chart.jpeg");
Response.ContentType = "image/jpeg";//设置Http的头信息
Response.BinaryWrite(content);//输出
Response.End();
}
#region 导出并下载
/// <summary>
/// 方法编号:14
/// 方法名称:ExportExcel
/// 内容摘要:将DataGrid中的数据导出到指定的Excel文件中
/// </summary>
/// <param name="page">Web页面对象</param>
/// <param name="dataGrid">包含被导出数据的DataGrid对象</param>
/// <param name="FileName">Excel文件的名称</param>
/// <param name="strTitle">导出Excel文件的标题</param>
/// <param name="iColspan">指定dataGrid的列数</param>
public static void ExportExcel(System.Web.UI.Page page,System.Web.UI.WebControls.DataGrid dataGrid,
string FileName,string strTitle,int iColspan)
{
System.Web.HttpResponse httpResponse = page.Response;
httpResponse.AppendHeader("Content-Disposition","attachment;filename="
+ HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8)); httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
httpResponse.ContentType ="application/ms-excel"; System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); //设置导出的Excel文件中的字体属性
hw.AddAttribute("style","FONT-FAMILY: 宋体;FONT-SIZE: 10pt"); //将DataGrid中的内容输入到hw对象中
dataGrid.RenderControl(hw); //在服务器上创建文件的路径和文件名
string filePath = System.Web.HttpContext.Current.Server.MapPath("../Doc/") + FileName;
System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
//写文件
//写入文件标题
sw.WriteLine("<table><tr><td align='center' colspan='" + iColspan + "'><font face='宋体' size=12px><b>"
+ strTitle + "</b></font></td></tr>");
//写入制表时间
sw.WriteLine("<tr><td colspan='" + iColspan + "' align='right'><font face='宋体' size=10px>制表时间:"
+ DateTime.Now.ToString("yyyy年MM月dd日") + "</font></td></tr></table>");
sw.Write(tw.ToString());
sw.Close(); //下载文件
DownFile(httpResponse,FileName,filePath);
httpResponse.End();
}
/// <summary>
/// 方法编号:16
/// 方法名称:DownFile
/// 内容摘要:提示用户导出的文件是打开还是保存
/// </summary>
/// <param name="Response">输出流对象</param>
/// <param name="fileName">下载的默认文件名</param>
/// <param name="fullPath">文件的全路径包括文件名</param>
private static bool DownFile(System.Web.HttpResponse Response,string fileName,string fullPath)
{
try
{
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment;filename=" +
HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) + ";charset=GB2312");
System.IO.FileStream fs= System.IO.File.OpenRead(fullPath);
long fLen=fs.Length; //每100K同时下载数据
int size=102400; //指定缓冲区的大小
byte[] readData = new byte[size]; //如果每次下载的数据大于文件的大小,改变下载数据大小为文件的大小
if(size > fLen)
{
size=Convert.ToInt32(fLen);
} long fPos=0;
bool isEnd=false; //读文件
while (!isEnd)
{
if((fPos+size)>fLen)
{
size=Convert.ToInt32(fLen-fPos);
readData = new byte[size];
isEnd=true;
} //读入一个压缩块
fs.Read(readData, 0, size);
Response.BinaryWrite(readData);
fPos+=size;
}
fs.Close();
//将服务器上的文件删除
System.IO.File.Delete(fullPath);
return true;
}
catch
{
return false;
}
}
非常感谢.如果需要分的话,我可以另开贴聊表谢意!
首先感谢您的帮助,我用了您的方法,在这一行的时候执行错误:dataGrid.RenderControl(hw);
错误消息:
异常详细信息: System.Web.HttpException: 类型“DataGridLinkButton”的控件“dgCard__ctl2__ctl0”必须放在具有 runat=server 的窗体标记内。 另外,我想请问一下,我不只是想将datagrid的数据导出,能不能我将查询到的数据一条条写到hw中,因为datagrid有分页,不知道您的数据能不能将所有分页的数据都导出!还有就是,如果可以导出所有分面的数据,我在一个frame中,怎么导出另一个frame中的datagrid的数据呢?
谢谢
{
Excel.Application excelApp;
Excel.Workbook workBook;
Excel.Worksheet worksheet;
Excel.Range range; int row = 1;
int cell = 1; try
{
excelApp = new Excel.Application();
workBook = excelApp.Workbooks.Add( XlWBATemplate.xlWBATWorksheet );
worksheet = ( Worksheet ) workBook.Worksheets[1];
}
catch( Exception exception )
{
Js.MessageBox( this.Page, exception.Message + "/r/n" + "An incompatible version of Microsoft Excel is intalled on your system." );
return;
} //Title
worksheet.Name = "统计";
worksheet.Cells[row, 1] = DateTime.Now.ToShortDateString();
range = ( Range ) worksheet.Cells[row, 1];
range.Font.Bold = true;
row += 2; string [] headers = new string []{ "服务商", "产品名称", "服务", "订阅", "取消" };
foreach( string header in headers )
{
worksheet.Cells[row, cell] = header;
range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
range.Font.Bold = true;
range.AutoFit();
cell++;
}
cell = 1;
row += 2; // create rows IList cps = Cps.GetContentProviders();
foreach( ContentProviderInfo contentProvider in cps )
{
// int cpRegion = cell;
worksheet.Cells[row, cell] = contentProvider.ContentProviderName;
range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
range.AutoFit();
cell++;
IList products = Products.GetProductsByCp( contentProvider.ContentProviderId, true );
foreach( ProductFlowInfo product in products )
{
int productRegion = cell;
worksheet.Cells[row, cell] = product.ProductName;
range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
range.AutoFit();
cell++; IList services = Products.GetProductServices( product.ProductId );
foreach( ProductServiceInfo service in services )
{
int serviceRegion = cell;
ServiceTypeInfo serviceType = Mobiles.GetServiceType( service.ServiceTypeId );
worksheet.Cells[row, cell] = serviceType.ServiceTypeName + "(" + Products.GetFeeTypeText( service.FeeType ) + ")";
range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
range.AutoFit();
cell++; worksheet.Cells[row, cell] = Statistics.GetCpStatisticCount( Convert.ToInt32( service.ServiceId ), StatisticStatus.Subscribed, ( StatisticTimeType ) Convert.ToInt32( timeTypeDropDownList.SelectedItem.Value ), Convert.ToDateTime( calendar.Text != string.Empty ? calendar.Text : DateTime.Now.ToShortDateString() ), cityDropDownList.SelectedItem.Value );
range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
range.AutoFit();
cell++; worksheet.Cells[row, cell] = Statistics.GetCpStatisticCount( Convert.ToInt32( service.ServiceId ), StatisticStatus.UnSubscribe, ( StatisticTimeType ) Convert.ToInt32( timeTypeDropDownList.SelectedItem.Value ), Convert.ToDateTime( calendar.Text != string.Empty ? calendar.Text : DateTime.Now.ToShortDateString() ), cityDropDownList.SelectedItem.Value );
range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
range.AutoFit(); row++;
cell = serviceRegion;
}
row++;
cell = productRegion;
}
row++;
cell = 1;
}
row++; string fileName = DateTime.Now.ToShortDateString() + ".xls";
string filePath = HttpContext.Current.Server.MapPath( fileName );
workBook.SaveCopyAs( filePath );
workBook.Close( false, null, null );
excelApp.Workbooks.Close();
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject( range );
System.Runtime.InteropServices.Marshal.ReleaseComObject( worksheet );
System.Runtime.InteropServices.Marshal.ReleaseComObject( workBook );
System.Runtime.InteropServices.Marshal.ReleaseComObject( excelApp );
range = null;
worksheet = null;
workBook = null;
excelApp = null;
GC.Collect(); System.IO.FileStream fileStream = System.IO.File.OpenRead( filePath );
byte[] fileData = new byte[ fileStream.Length ];
fileStream.Read( fileData, 0, ( int ) fileStream.Length );
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader( "Content-Type", "application/vnd.ms-excel" );
fileName = System.Web.HttpUtility.UrlEncode( System.Text.Encoding.UTF8.GetBytes( fileName ) );
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename="+ System.Convert.ToChar(34) + fileName + System.Convert.ToChar(34) );
HttpContext.Current.Response.AddHeader("Content-Length", fileStream.Length.ToString() );
HttpContext.Current.Response.BinaryWrite( fileData );
fileStream.Close();
System.IO.File.Delete( filePath );
HttpContext.Current.Response.End(); }
DataGrid.AllowPaging = false;然后再调用绑定的方法重新绑定一次后再导出就可以了,这样的话,就将数据源中的所有数据都导出来了,这样不是更好吗?再提醒一点,或者当你在用模板列时,当模板列中加了一个Button时,在导出时也要处理一下,DataGrid.Columns[8].Visible = false;
这样就不会有错误了。以上的这些并不会改变DataGrid的样式,只是对导出来的数据产生变化。
这个方法的好处是可以保持DataGrid的原样式,并且速度还快。你所说的导出另一个frame的问题也可以的,只要能访问到这个DataGrid并且按照我上边所提示的处理一下就可以了。
#region 将DataTable中数据导出到EXCEL中
/// <summary>
/// 将DataTable中数据导出到EXCEL中
/// </summary>
/// <returns>返加明文字符串</returns>
public static void ExportExcel(DataTable dataTable,Page page)
{
HttpResponse resp;
resp = page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
string colHeaders= "", ls_item="";
int i=0;
DataRow[] myRow=dataTable.Select("");
for(i=0;i<dataTable.Columns.Count-1;i++)
{
colHeaders+=dataTable.Columns[i].Caption.ToString()+"\t";
}
colHeaders +=dataTable.Columns[i].Caption.ToString() +"\n";
//向HTTP输出流中写入取得的数据信息(表头信息)
resp.Write(colHeaders);
//逐行处理数据
foreach(DataRow row in myRow)
{
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
for(i=0;i<row.Table.Columns.Count-1;i++)
ls_item +=row[i].ToString() + "\t";
ls_item += row[i].ToString() +"\n";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item);
ls_item="";
}
resp.End();
}
#endregion