티스토리 뷰


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.IO;

public partial class T1_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

//파일명 생성하기
private string getFileName()
{
return "UnitTestResult_" + DateTime.Now.ToShortDateString().Replace(" ", "_") + "_" + DateTime.Now.ToShortTimeString().Replace(" ", "_").Replace("오전", "AM").Replace("오후", "PM").Replace(":", "_") + "_" + DateTime.Now.Millisecond.ToString();
}

// 엑셀파일 생성하기
protected void Button2_Click(object sender, EventArgs e)
{
string strFileName = getFileName();

try
{
string xls = "D:\\UnitTestResult\\" + strFileName;
if (System.IO.File.Exists(xls))
{
System.IO.File.Delete(xls);
}

//실제 엑셀파일 생성(OleDB 이용)
string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=D:\\UnitTestResult\\" + strFileName + @";Extended Properties=Excel 8.0";
OleDbConnection connection = new OleDbConnection(strConnectionString);
connection.Open();

string sql = "Create Table Test(숫자 int)";
OleDbCommand command = new OleDbCommand(sql, connection);
command.ExecuteNonQuery();

for (int i = 0; i <= 100; i++)
{
string sql1 = "insert into test values('" + i.ToString() + "')";
OleDbCommand command1 = new OleDbCommand(sql1, connection);
command1.ExecuteNonQuery();
}

connection.Close();
this.Download(strFileName);

}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

// 사용자에게 파일 다운로드 강제로 시키기
protected void Download(string strFileName)
{
if (strFileName == null)
{
Response.End();
}
else
{
string pFileName = strFileName + ".xls";

Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlPathEncode(pFileName));
Response.WriteFile("D:\\UnitTestResult\\" + pFileName);
Response.End();
}
}
}

반응형

'컴퓨터 이야기 > 서버 관리' 카테고리의 다른 글

Mail 서버 DNS 설정  (0) 2011.10.15
댓글