using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using System.Web.Configuration;
namespace testexcel
{
public partial class createcsv : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Charset = "tis-620";
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };
DataRow dr = dt.NewRow();
dr["ID"] = 1;
dr["name"] = "ทดสอบ";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 2;
dr["name"] = "B";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 3;
dr["name"] = "C";
dt.Rows.Add(dr);
CreateCSVFile(dt, "c:\\dell\\csvData.csv");
}
public void CreateCSVFile(DataTable dt, string strFilePath)
{
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}
}
Tag : ASP.NET, Excel (Excel.Application), Web (ASP.NET), C#