/// <summary>
/// 将DataGrid中数据导出至Excel,生成标准的Excel文件
/// </summary>
/// <param name="grid">DataGrid控件ID</param>
/// <param name="fileName">导出文件名</param>
protected void ExportToExcel(System.Web.UI.WebControls.DataGrid grid,string fileName)
{
string templetFilePath;
templetFilePath = Server.MapPath("../").ToString() + @"Template\";
object missing = System.Reflection.Missing.Value;
Excel.Application app;
Excel.Workbook workBook;
Excel.Worksheet workSheet;
Excel.Range range;
//创建一个Application对象并使其不可见
app = new Excel.ApplicationClass();
app.Visible=false;
//创建一个WorkBook对象
workBook = app.Workbooks.Add(missing);
//得到WorkSheet对象
workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
int rowCount = grid.Items.Count + 1; //DataTable行数+GirdHead
int colCount = 13;//grid.Columns.Count; //DataTable列数
//利用二维数组批量写入
string[,] arr = new string[rowCount, colCount];
for (int j = 0; j < rowCount; j++)
{
for (int k = 0; k < colCount; k++)
{
if (j == 0)
{
arr[j, k] = grid.Columns[k].HeaderText;
}
else
{
arr[j, k] = grid.Items[j - 1].Cells[k].Text.ToString();
}
}
}
range = (Excel.Range)workSheet.Cells[1, 1]; //写入Exel的坐标
range = range.get_Resize(rowCount, colCount);
range.Value = arr;
workBook.SaveAs(templetFilePath + fileName, missing, missing, missing, missing, missing,Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing);
if (workBook.Saved)
{
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Quit();
}
if (range != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range = null;
}
if (workSheet != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
workSheet = null;
}
if (workBook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
workBook = null;
}
if (app != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
GC.Collect();//强制代码垃圾回收
//下载文件
DownLoadFile(templetFilePath,fileName);
}在range = range.get_Resize(rowCount, colCount);这行会出错,帮忙看看,谢谢
/// 将DataGrid中数据导出至Excel,生成标准的Excel文件
/// </summary>
/// <param name="grid">DataGrid控件ID</param>
/// <param name="fileName">导出文件名</param>
protected void ExportToExcel(System.Web.UI.WebControls.DataGrid grid,string fileName)
{
string templetFilePath;
templetFilePath = Server.MapPath("../").ToString() + @"Template\";
object missing = System.Reflection.Missing.Value;
Excel.Application app;
Excel.Workbook workBook;
Excel.Worksheet workSheet;
Excel.Range range;
//创建一个Application对象并使其不可见
app = new Excel.ApplicationClass();
app.Visible=false;
//创建一个WorkBook对象
workBook = app.Workbooks.Add(missing);
//得到WorkSheet对象
workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
int rowCount = grid.Items.Count + 1; //DataTable行数+GirdHead
int colCount = 13;//grid.Columns.Count; //DataTable列数
//利用二维数组批量写入
string[,] arr = new string[rowCount, colCount];
for (int j = 0; j < rowCount; j++)
{
for (int k = 0; k < colCount; k++)
{
if (j == 0)
{
arr[j, k] = grid.Columns[k].HeaderText;
}
else
{
arr[j, k] = grid.Items[j - 1].Cells[k].Text.ToString();
}
}
}
range = (Excel.Range)workSheet.Cells[1, 1]; //写入Exel的坐标
range = range.get_Resize(rowCount, colCount);
range.Value = arr;
workBook.SaveAs(templetFilePath + fileName, missing, missing, missing, missing, missing,Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing);
if (workBook.Saved)
{
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Quit();
}
if (range != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range = null;
}
if (workSheet != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
workSheet = null;
}
if (workBook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
workBook = null;
}
if (app != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
GC.Collect();//强制代码垃圾回收
//下载文件
DownLoadFile(templetFilePath,fileName);
}在range = range.get_Resize(rowCount, colCount);这行会出错,帮忙看看,谢谢
{
/// <summary>
/// 把DataTable导入到EXCEL
/// </summary>
/// <param name="dt">DataTable的名称</param>
public System.IO.StringWriter ExportToExcel(System.Data.DataTable dt)
{
System.IO.StringWriter sw=new StringWriter();
string OutputString="";
int iRow;
int iCol;
for(iCol=0;iCol<dt.Columns.Count;iCol++) //输入列名到缓存
{
OutputString=OutputString+"\t"+dt.Columns[iCol].ColumnName;
}
sw.WriteLine(OutputString.Trim());
sw.WriteLine(); for(iRow=0;iRow<dt.Rows.Count;iRow++)
{
OutputString="";
for(iCol=0;iCol<dt.Columns.Count;iCol++)
{
OutputString=OutputString+"\t"+dt.Rows[iRow][iCol].ToString();
}
sw.WriteLine(OutputString.Trim());
}
return sw;
}
方法土了点,用IO流直接写,调用时这样写:
System.IO.StringWriter sw=ex.ExportToExcel(dataSet1.Tables[0]); Response.AddHeader("Content-Disposition", "attachment; filename=ReportExport.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End(); sw.Close ();
Response.ContentType = "application/ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End(); sw.Close ();
在调用的时候有问题!
在调用的前面这样写
{
System.IO.StringWriter sw=ex.ExportToExcel(ds.Tables[0]); Response.AddHeader("Content-Disposition", "attachment; filename=ReportExport.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End(); sw.Close (); }出现这样的错误: 找不到类型或命名空间名称“ex”(是否缺少 using 指令或程序集引用?)
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
//filename=fileflow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
Response.AppendHeader("content-disposition", "attachment;filename=a.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
//response.contenttype指定文件类型 可以为application/ms-excel、application/ms-word、application/ms-txt、application/ms-html 或其他浏览器可直接支持文档
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
// 定义一个输入流
System.IO.StringWriter ostringwriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter ohtmltextwriter = new System.Web.UI.HtmlTextWriter(ostringwriter);
this.DataGrid1.RenderControl(ohtmltextwriter);
//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.rendercontrol()属性的控件
Response.Write(ostringwriter.ToString());
Response.End();
{
string sql = "select convert(varchar(10),detailtime,111) as 申請時間,detaildept as 申請單位,shenqingren as 申請人,convert(varchar(10),fromdaytime,111) as 日期從,fromhour as 時間從,convert(varchar(10),todaytime,111) as 日期止,tohour 時間止,carno as 車號,driver as 駕駛員 from gc_carinout where detaildept = '" + DropDownList1.SelectedValue + "' and [check] = 'C'";
SqlConnection conn = sda.getsqlconnection();
SqlDataAdapter sda1 = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
sda1.Fill(ds, "Report");
DataTable dt = new DataTable();
dt = ds.Tables["Report"];
DSToExcel(dt);
} private void DSToExcel(DataTable dt)
{
string strFile = "";
string path = "";
strFile = strFile + "DeptQueryReport_";
strFile = strFile + DateTime.Now.ToString("yyyyMMddHHmm");
strFile = strFile + ".xls";
string fileName = strFile;
path = Server.MapPath(strFile);
System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
sw.Write("申請時間");
sw.Write("\t");
sw.Write("申請單位");
sw.Write("\t");
sw.Write("申請人");
sw.Write("\t");
sw.Write("日期從");
sw.Write("\t");
sw.Write("日期止");
sw.Write("\t");
sw.Write("車號");
sw.Write("\t");
sw.Write("駕駛員");
sw.Write("\t");
sw.WriteLine(""); for (int i = 0; i < dt.Rows.Count; i++)
{
sw.Write(dt.Rows[i]["申請時間"].ToString());
sw.Write("\t");
sw.Write(dt.Rows[i]["申請單位"].ToString());
sw.Write("\t");
sw.Write(dt.Rows[i]["申請人"].ToString());
sw.Write("\t");
sw.Write(dt.Rows[i]["日期從"].ToString());
sw.Write("\t");
sw.Write(dt.Rows[i]["日期止"].ToString());
sw.Write("\t");
sw.Write(dt.Rows[i]["車號"].ToString());
sw.Write("\t");
sw.Write(dt.Rows[i]["駕駛員"].ToString());
sw.Write("\t");
}
sw.Flush();
sw.Close();
try
{
if (path != "")
{
DownFile(path, fileName);
}
}
catch (Exception e)
{
Response.Write(e);
Response.Write("failed");
}
} private void DownFile(string filePath, string fileName)
{
FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("Big5");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
fileInfo.Delete();
Response.End();
}
{HttpResponse resp;resp = Page.Response;resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");resp.ContentType = "application/ms-excel";resp.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");string colHeaders = "", ls_item = "";int i = 0;//定义表对象与行对像,同时用DataSet对其值进行初始化 DataTable dt = ds.Tables[0];DataRow[] myRow = dt.Select("");//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符 for (i = 0; i < ds.Tables[0].Columns.Count; i++)colHeaders += dt.Columns[i].Caption.ToString() + "\t";colHeaders += "\n";//向HTTP输出流中写入取得的数据信息 resp.Write(colHeaders);//逐行处理数据 foreach (DataRow row in myRow)
{//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n for (i = 0; i < ds.Tables[0].Columns.Count; i++)ls_item += row[i].ToString() + "\t";ls_item += "\n";//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据 resp.Write(ls_item);ls_item = "";}resp.End();}
{
if(Request.QueryString["bExcel"] == "1")
{
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = ""; //关闭 ViewState
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
//此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
//获取control的HTML
DataGrid1.RenderControl(hw);//将DATAGRID中的内容输出到HtmlTextWriter对象中
// 把HTML写回浏览器
Response.Write(tw.ToString());
Response.End(); }
private void LinkButton1_Click(object sender, System.EventArgs e)
{
Response.Redirect("../stock/print_this_list.aspx?bExcel=1"); //本页地址
}
/// DataGrid中的数据导入到Word和Excel
/// </summary>
/// <param name="FileType">文件类别(application/ms-excel、application/ms-word)</param>
/// <param name="FileName">文件名</param>
public static void ExportDataGrid(string FileType, string FileName, System.Web.UI.Page page, params System.Web.UI.WebControls.WebControl[] webCtrl) //从DataGrid导出
{
System.Web.HttpContext.Current.Response.Charset = "GB2312";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
System.Web.HttpContext.Current.Response.ContentType = FileType;
page.EnableViewState = false; StringWriter tw = new StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
for (int i = 0; i < webCtrl.Length; i++)
{
webCtrl[i].RenderControl(hw);
}
System.Web.HttpContext.Current.Response.Write(tw.ToString());
System.Web.HttpContext.Current.Response.End();
}
Response.Charset = "";
this.Button1.Visible=false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
this.DataGrid1.RenderControl(hw);
http://www.cnblogs.com/ilovejolly/archive/2006/11/01/546553.html
Response.Charset = "";
this.Button1.Visible=false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
this.DataGrid1.RenderControl(hw);
的方法生成的不是标准的EXCEL,而是后缀名是XLS的文件用这个方法要注意的是DATAGRID里面有些不能用,如分页,按钮列等等 建议做张隐藏的DATAGRID 不带分页和按钮列的就可以
这个是讲师邵志东的一个例子,我刚才实验成功的
有更多的需要你可以去这里看一下http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/consyscourse/ASPNETpractise.aspx
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection conn=new SqlConnection ("server=.;database=InformationManagement;uid=sa;pwd=sa;");
SqlDataAdapter da=new SqlDataAdapter("select * from area",conn);
DataSet ds=new DataSet();
conn.Open();
da.Fill(ds);
this.DataGrid1.DataSource=ds.Tables[0].DefaultView;
this.DataGrid1.DataBind();
}
导出按钮点击事件private void Button1_Click(object sender, System.EventArgs e)
{
Response.ContentType = "application/vnd.ms-excel";
this.Button1.Visible=false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
this.DataGrid1.RenderControl(hw);
}
就datagrid 或者dataset 直接导出到excel啊!谢谢了!很急 啊!
Response.Clear();
Response.Buffer= true;
Response.Charset="GB2312";
//下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
//filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
// 定义一个输入流
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); DataGrid dg2=new DataGrid();
.DataSource=dt_news;
dg2.DataBind();
dg2.RenderControl(oHtmlTextWriter);
//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
Response.Write(oStringWriter.ToString());
Response.End();
先一个显示数据页面,有个GRID,一个导出按钮,点击导出按钮就跳到一个专门导出EXCEL的页面,这个页面只有个grid
显示页面,grid绑定的时候加一句
Context.Cache.Insert("Data",dt, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);
把数据集存到缓存
然后导出按钮事件就是跳转页面就可以了
下面是专门导出EXCEL的页面代码
EXEXCEL.ASPX
<HTML>
<HEAD>
<title>ExpExcel</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="宋体">
<TABLE id="Table1" cellSpacing="1" cellPadding="1" width="100%" border="0">
<TR>
<TD width="5%" height="10%"></TD>
<TD height="10%"></TD>
<TD width="5%" height="10%"></TD>
</TR>
<TR>
<TD width="5%"></TD>
<TD vAlign="top" align="center">
<asp:datagrid id="DataGrid1" runat="server" AllowSorting="True" CssClass="sys_grid" Width="100%">
<ItemStyle Height="25px"></ItemStyle>
<HeaderStyle Height="25px" HorizontalAlign="Center" CssClass="sys_grid_head_cell"></HeaderStyle>
<PagerStyle Visible="False"></PagerStyle>
</asp:datagrid></TD>
<TD width="5%"></TD>
</TR>
<TR>
<TD width="5%" height="10%"></TD>
<TD height="10%"></TD>
<TD width="5%" height="10%"></TD>
</TR>
</TABLE>
</FONT>
</form>
</body>
</HTML>
EXEXCEL.ASPX.CSusing System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;namespace pmsx.aspx
{
/// <summary>
/// ExpExcel 的摘要说明。
/// </summary>
public class ExpExcel : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
string sel=Request.Params["sel"].ToString();
try
{
if(BindGrid()==0)
{
string strJava="<script language=javascript>window.alert('数据不存在,可能需要重新查询!');</script>";
this.RegisterStartupScript("Alert",strJava);
return;
}
}
catch
{
string strJava="<script language=javascript>window.alert('出现异常,确认是否操作正确或重新查询!');</script>";
this.RegisterStartupScript("Alert",strJava);
return;
}
this.EnableViewState=false;
Response.ContentType ="application/vnd.ms-excel";//导出EXCEL数据
Response.AddHeader("Content-Disposition","attachment; filename=ExpExcel.xls");
}
}
int BindGrid()
{
System.Data.DataTable dt=(System.Data.DataTable)Cache["Data"];
if(dt==null)
return 0;
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
return 1;
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load); }
#endregion
}
}
将DataGrid控件中的数据导出ExeclSystem.Web.UI.Control ctl=this.DataGrid1;
//DataGrid1是你在窗体中拖放的控件
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
如果你的DataGrid用了分页,它导出的是当前页的信息,也就是它导出的是DataGrid中显示的信息。而不是你select语句的全部信息。为方便使用,写成方法如下:public void DGToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
} 用法:DGToExcel(datagrid1);