c# 엑셀(Excel) 숫자형식 텍스트로 처리하는 방법
c# 에서 개발시에 엑셀 파일로 저장할 경우 숫자형식이 아닌데, 숫자형식으로 지정이 되어 곤란할 떄가 있다.
00001 같은 경우 1로 보여질떄 =ㅁ=; 대략 난감..
이럴 경우 셀 자체를 TEXT 형식으로 인식하도록 처리하여야 한다.
이럴 경우
기존 소스
public override void ExecuteResult(ControllerContext context)
{
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + this.FileName);
if (!HttpContext.Current.Request.IsSecureConnection) //http 통신일만 캐시 적용
{
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Charset = "UTF-8";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.BinaryWrite(Encoding.UTF8.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.ExcelGridView.RenderControl(htw);
byte[] byteArray = Encoding.UTF8.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.UTF8);
curContext.Response.Write(sr.ReadToEnd());
curContext.Response.End();
}
변경된 소스
public override void ExecuteResult(ControllerContext context)
{
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + this.FileName);
if (!HttpContext.Current.Request.IsSecureConnection) //http 통신일만 캐시 적용
{
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Charset = "UTF-8";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.BinaryWrite(Encoding.UTF8.GetPreamble());
StringWriter sw = new StringWriter();
string style = @"<style> TD { mso-number-format:\@; } </style>";
sw.Write(style);
HtmlTextWriter htw = new HtmlTextWriter(sw);
this.ExcelGridView.RenderControl(htw);
byte[] byteArray = Encoding.UTF8.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.UTF8);
curContext.Response.Write(sr.ReadToEnd());
curContext.Response.End();
}
위와 같이
string style = @"<style> TD { mso-number-format:\@; } </style>";
sw.Write(style);
부분을 추가해 주시면 엑셀(EXCEL) 에서 포맷을 숫자로 인식하지 않고, 텍스트로 인식한다.