C#GridView 데이터를 Excel 파일 클래스로 내보내기
7686 단어 GridView
using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
namespace DotNet.Utilities
{
public class ExportExcel
{
protected void ExportData(string strContent, string FileName)
{
FileName = FileName + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//this.Page.EnableViewState = false;
// , " / "
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");
//
HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
HttpContext.Current.Response.Write(strContent);
HttpContext.Current.Response.Write("</body></html>");
//
//Response.End();
}
/// <summary>
/// Excel
/// </summary>
/// <param name="obj"></param>
public void ExportData(GridView obj)
{
try
{
string style = "";
if (obj.Rows.Count > 0)
{
style = @"<style> .text { mso-number-format:\@; } </script> ";
}
else
{
style = "no data.";
}
HttpContext.Current.Response.ClearContent();
DateTime dt = DateTime.Now;
string filename = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ExportData" + filename + ".xls");
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
obj.RenderControl(htw);
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
catch
{
}
}
}
}
// : http://www.sharejs.com/codes/csharp/8624
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
C#의 413은 DataGridView에서 Excel로 데이터 내보내기텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.