首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

实例,将GridView中数据导入到Excel表中()

2012-06-11 
求一个实例,将GridView中数据导入到Excel表中(在线等)如题!要一个完整的实例,能运行![解决办法]看看这个可

求一个实例,将GridView中数据导入到Excel表中(在线等)
如题!要一个完整的实例,能运行!

[解决办法]
看看这个可以吗:http://blog.csdn.net/hhxxcj/archive/2009/01/14/3772552.aspx
[解决办法]
http://www.cnblogs.com/activer/archive/2006/08/27/487749.html
[解决办法]
如果是分页的情况下:

using OWC; 
using System.Data.OleDb; 
using System.IO; 

SpreadsheetClass xlsheet=new SpreadsheetClass(); 
conn.Open(); 
cmd=new OleDbCommand(sql,conn); 
OleDbDataReader reader=cmd.ExecuteReader(); 
int numbercols=reader.FieldCount; 
int row=2; 
int i=0; 
//输出标题 
for(i=0;i <numbercols;i++) 

xlsheet.ActiveSheet.Cells[1, i + 1] = reader.GetName(i).ToString(); 


// 输出字段内容 
while(reader.Read()) 

for(i=0;i <numbercols;i++) 

xlsheet.ActiveSheet.Cells[row, i + 1] = reader.GetValue(i).ToString(); 

row = row + 1; 


reader.Close(); 
conn.Close(); 
try 

xlsheet.ActiveSheet.Export(Server.MapPath( ". ") + "\\mfExcel\\ " + this.xlfile.Text+ ".xls ",OWC.SheetExportActionEnum.ssExportActionNone); 

catch(System.Runtime.InteropServices.COMException e ) 

Response.Write( "错误: " + e.Message); 

 
 
 

[解决办法]
http://www.tzwhx.com/newOperate/html/1/11/111/493.html
[解决办法]

[解决办法]

C# code
public partial class GridViewToExcel : System.Web.UI.Page{        GridView gridToExport = null; protected void Page_Load(object sender, EventArgs e)    {    }    /// <summary>    /// 必须override这个方法,否则会报错    ///     /// "Control 'ctl00_MainContent_Gridview1' of type 'GridView' must be placed    /// inside a form tag with runat=server",     /// even though you have the supposedly missing form tag.    ///     /// </summary>    /// <param name="control"></param>    public override void VerifyRenderingInServerForm(Control control)    {        //base.VerifyRenderingInServerForm(control);    }    protected void btnExport_Click(object sender, EventArgs e)    {        gridToExport = gvwEmployee;    }    protected override void Render(HtmlTextWriter writer)    {        if (gridToExport as GridView != null)        {            ExportGridToExcel(gridToExport, "test.xls");        }        base.Render(writer);    }       private void ExportGridToExcel(GridView grid, string filename)    {        // 检查是否有文件名        if (string.IsNullOrEmpty(filename))        {            throw new ArgumentException("Export filename is required");        }        // 检查是否是excel格式        if (!filename.EndsWith(".xls"))        {            filename += ".xls";        }        grid.AllowPaging = false;  // 禁止分页        grid.AllowSorting = false; // 禁止排序        grid.DataBind();            // 绑定数据        StringWriter tw = new StringWriter();        HtmlTextWriter hw = new HtmlTextWriter(tw);        Response.Clear();        Response.ContentType = "application/vnd.ms-excel";        Response.AddHeader("content-disposition", "attachment;filename=" + filename);        Response.Charset = string.Empty;        Page.EnableViewState = false;        grid.RenderControl(hw);        Response.Write(tw.ToString());        Response.End();    }} 


[解决办法]

探讨
可以了,但是打开Excel,Excel没有表格线,怎么保留表格线框???

[解决办法]

[解决办法]
protected void ToExcel(object sender, EventArgs e)
{
HttpContext.Current.Response.Clear();//清除缓冲区流中的所有的内容输出
HttpContext.Current.Response.Buffer = true;//获取一个值,该值指示是否缓冲输出,并在完成处理整个响应之后将其发送
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls");//.xls 将http头添加到输出流 DateTime.Now.DayOfYear.ToString()
HttpContext.Current.Response.ContentEncoding = Encoding.UTF7;//设置输出流的http字符集
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";//设置输出流的http MiMe类型
CultureInfo formatProvider = new CultureInfo("ZH-CN", true);//提供有关特定区域性的信息及如何设置日期和排序字符串的格式
StringWriter stringwriter = new StringWriter(formatProvider);//实现一个用于将字符串写入System.IO.TextWriter,该信息存储在基础System.Text.StringBulider中
HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);//将标记字符和文本写入到Asp.net服务器控件输出流,此类提供Asp.net服务器控件在向客户端呈现标记时所使用的格式设置功能


//控制GridView分页的
int curPageIndex = this.DGBatchForm.CurrentPageIndex;
int curPageSize = DGBatchForm.PageSize;
DGBatchForm.AllowPaging = false;
DGBatchForm.RenderControl(htmlwriter);//将服务器控件的内容输出到所提供的System.Web.UI.HtmlTextWriter对象中,如果已启用跟踪功能,则存储有关控件的跟踪信息

DGBatchForm.AllowPaging = true;
DGBatchForm.CurrentPageIndex = curPageIndex;
DGBatchForm.PageSize = curPageSize;

HttpContext.Current.Response.Write(stringwriter.ToString());//将一个字符数组写入http相应数据流
HttpContext.Current.Response.End();//将当前的所有缓冲的输出发送到客户端,停止该页的执行,并引发//System.Web.httpApplication.EndRequest事件
return;
}
[解决办法]
调用我的这个方法吧!很好! 很强大!
传入个DataTable,就将你的数据导出:

/// <summary>
/// 将数据写入到流当中
/// </summary>
/// <param name="tblSchema">填充当前Datagrid的DataTable对象</param>
public void CreateStreamCSV(DataTable tblSchema)
{
StringBuilder Str = new StringBuilder();
char c = ',';

StringWriter sw = new StringWriter();
for (int i = 0; i < tblSchema.Columns.Count; i++)
{
Str.Append(tblSchema.Columns[i].Caption + c);
}
Str.Append("\r\n");
for (int i = 0; i < tblSchema.Rows.Count; i++)
{
for (int j = 0; j < tblSchema.Columns.Count; j++)
{
if (tblSchema.Rows[i][j].ToString().ToUpper().Equals("TRUE"))
Str.Append("是" + c);
else if (tblSchema.Rows[i][j].ToString().ToUpper().Equals("FALSE"))
Str.Append("否" + c);
else if(tblSchema.Rows[i][j].ToString().IndexOf("0:00")!=-1)//判断是否是日期,true则取得短日期格式
Str.Append(Convert.ToDateTime(tblSchema.Rows[i][j].ToString()).ToShortDateString() + c);
else
Str.Append(tblSchema.Rows[i][j].ToString() + c);
}
Str.Append("\r\n");
}
sw.Write(Str);
sw.Close();
string dataTime = (System.DateTime.Now.GetDateTimeFormats('s')[0].ToString().Substring(0,10) + System.DateTime.Now.TimeOfDay.ToString()).Replace(":", "");


dataTime = dataTime.Replace("-","");
dataTime = dataTime.Replace(".","");
dataTime = dataTime.Replace("_","");
dataTime = dataTime.Substring(0, 17);
string Filename = dataTime +SetRadomNum();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Filename + ".csv");
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
System.Web.HttpContext.Current.Response.Write(sw);
sw.Flush();
System.Web.HttpContext.Current.Response.End();
}

热点排行