サードパーティのdllを使用せずに、グリッドデータをASP.NetWebページからExcelにエクスポートしたい。
誰かがそれを行う方法を教えてもらえますか?
Bullted List、 RadioButtonList 、 CheckBoxList などの GridView のテンプレート フィールドで任意のコントロールを使用し、そのまま Excel にエクスポートする場合は、次のコードのみを使用することをお勧めします ...
public void ExportToExcel(GridView gv, 文字列ファイル名)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", filename + ".xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
(StringWriter sw = new StringWriter()) を使用して
{
(HtmlTextWriter htw = new HtmlTextWriter(sw)) を使用して
{
// グリッドを含むテーブルを作成します
テーブル table = new Table();
// グリッド線の設定を含める
table.GridLines = gv.GridLines;
// テーブルにヘッダー行を追加します
if (gv.HeaderRow != null)
{
// PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
//ヘッダーをカラフルにする
for (int j = 0; j
それ以外の場合は、Grid をバインドして Excel にデータをエクスポートする DataTable を使用することをお勧めします。そのためには、次のコードを使用します。
public void ExportToExcel(DataTable dt, string fileName)
{
試す
{
//****************************Excel生成開始******************** ********
string attachment = "attachment; filename="+fileName+".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
文字列タブ = "";
foreach (dt.Columns の DataColumn dc)
{
Response.Write(タブ + dc.ColumnName);
タブ = "\t";
}
Response.Write("\n");
int ik;
foreach (dt.Rows の DataRow dr)
{
タブ = "";
for (ik = 0; ik
こんにちは、以下のコードを使用して Excel にエクスポートしてください:
FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1; //This is the same dataTable by which you are binding your grid
DataGrd.DataBind();
DataGrd.RenderControl(htmlWrite);
string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
stringWriter.ToString().Normalize();
vw.Write(stringWriter.ToString());
vw.Flush();
vw.Close();
WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());
上記のコードでは、添付ファイルを Response オブジェクトでユーザーにプッシュする WriteAttachment 関数を使用しています。次のコードは、WriteAttachment の実装を示しています。
public static void WriteAttachment(string FileName, string FileType, string content)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}
詳細については、ここをクリックしてください