日期:2014-05-17  浏览次数:20486 次

asp.net 数据导成excel
在ASP.NET中如何将gridview控件中的数据导成excel中,希望附带代码谢谢

------解决方案--------------------
string attachment = "attachment; filename=stuinfo.xls";
HttpResponse Response = HttpContext.Current.Response;
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw); // Create a form to contain the grid
HtmlForm frm = new HtmlForm();

gdv_Data_HrMoonReport.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(gdv_Data_HrMoonReport);
frm.RenderControl(htw); //GridView1.RenderControl(htw);
Response.Charset = "UTF-8 ";
//Response.ContentEncoding =System.Test.Encoding.GetEncoding("UTF-8 ");
Response.Write(sw.ToString());
Response.End();


gdv_Data_HrMoonReport 是gridview的id


------解决方案--------------------
//导出Excel
protected void ExportExcel(System.Data.DataTable dt)
{
if (dt == null || dt.Rows.Count == 0) return;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

if (xlApp == null)
{
return;
}
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range;
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
}
xlApp.Visible = true;
}
//给DataTable赋值
public void GenerateExcel()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(string));
DataRow dr = dt.NewRow();
dr["Name"] = "spring";
dr["Age"] = "20";
dt.Rows.Add(dr);
dt.AcceptChanges();
ExportExcel(dt);
}
protected void Button1_Click(object sender, EventArgs e)
{
GenerateExcel();
}