개발팁2016. 9. 1. 10:29

엑셀 다운로드 구현시 html 의 table 태그로 구성된 파일로 내려받기를 하는경우,

 

ContentType 을 application/vnd.ms-excel
하고, 출력을 하면, 자동으로 엑셀로 열리게 되는데,

 

이때 엑셀에서는, 본문에 있는 셀 데이터 (table 태그) 값에 따라,
자료형을 자동으로 인식하게 된다.

 

000212 이런값이 있을경우, 엑셀에서는 숫자로 인식하여,
앞에 0을 떼어버리고, 212 로 출력을 하게 된다.

 

이러한 현상을 해결하기 위해서는 해당 컬럼이 문자라는것을 인식시켜줄 필요가 있다.

 

<style>
body {
    font-size:12px;
    font-family: 맑은 고딕;
}

table {
    font-size:12px;
    text-align:center;
}
table th {
    text-align:center;
    height:28px;
    background-color: #f0f0f0;
}
table td {
    text-align:left;
    height:26px;
    mso-number-format:"\@";
}

.number {
    text-align:right !important;
    mso-number-format:General !important;
    white-space:nowrap !important;
}
</style>

 

html 파일의 head 태그 사이에, 위와 같이 css 를 정의해보자.
mso-number-format 은 MS Office 에서 숫자 포맷관련 stylesheet 속성이다.

 

 <table border="1">
    <tr>
        <th>발주일</th>
        <th>C/D 번호</th>
        <th>순번</th>
        <th>부품번호</th>
        <th>부품명</th>
        <th>수량</th>
    </tr>
    <tr>
        <td>2016-08-31</td>
        <td>00212</td>
        <td class="number">1</td>
        <td>HGTG5026</td>
        <td>INLAY CARRIER SET FOR MACH2XS 15G</td>
        <td class="number">11</td>
    </tr>
</table>

 

이제 본문을 table th td 로 구성하면, 자동으로 문자로 인식하도록 한다.
단, 실제 숫자로 인식해야 할 곳에는, class="number" 만 지정해주면 된다.

 

 

 

Posted by 헝개
개발팁2016. 7. 20. 09:41

ASP.NET 의 View 를 ViewEngine 으로 렌더링해서 나온 HTML 을 엑셀로 내려받는 방법이다.

 

아래와 같이 2개의 정적 메서드를 정적 클래스 (static class) 안에 정의한다.

 

// Copyright 헝그리개발자​(http://bemeal2.tistory.com)
// 소스는 자유롭게 사용가능합니다. Copyright 는 삭제하지 마세요.

// HTML 을 엑셀파일로 웹 다운로드
public static void ToExcelDownload(this string strHTML, string filename)
{
    filename = filename.Replace(" ", "_");



    HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename));
    HttpContext.Current.Response.Charset = "";
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    HttpContext.Current.Response.Write(strHTML);
    HttpContext.Current.Response.End();
}



// View 를 HTML 문자열로 변환
public static string ViewToString(this ControllerContext controller, string viewName, ViewDataDictionary ViewData, TempDataDictionary TempData, object model)
{
    ViewData.Model = model;
    using (var sw = new StringWriter())
    {
         var viewResult = ViewEngines.Engines.FindPartialView(controller, viewName);
         var viewContext = new ViewContext(controller, viewResult.View, ViewData, TempData, sw);
         viewResult.View.Render(viewContext, sw);
         viewResult.ViewEngine.ReleaseView(controller, viewResult.View);


         return sw.GetStringBuilder().ToString();
    }
}

 

ToExcelDownload 메서드는 문자열(html)을 엑셀타입으로 내려받도록 해준다.

실제 내용은 table 테그로 구성된 html 이지만, 엑셀 형식으로 다운로드하도록 해주는 것이다.

 

ViewToString 메서드는 ViewContext 로, View 를 렌더링해서 String 으로 만들어준다.

 

 

엑셀 다운로드 버튼에 대한 Controller 를 아래와 같이 정의할 수 있다.

Model 을 구성하여, ViewToString 으로 View 이름과 Model 객체를 전달하여 준다.

예제에서는 Controller 이름과 동일한 이름의 View 이름을 사용하였다.

 

이 말은, 현재 Controller 의 View 를 호출하여 렌더링 한다는 뜻이다.

물론, 다른 Controller 의 View 이름을 넣어주어도 상관이 없다. 해당 View 에 맞는 Model 만 생성해서 전달해주면 된다.

 

 // 엑셀 다운로드에 대한 컨트롤러
public ActionResult Sample_ExcelDownload(int key_id)
{
    MySampleDataContainer model = new MySampleDataContainer();



    BizSample biz = new BizSample();
    model.header = biz.SampleDataInfo(key_id);
    model.list = biz.SampleDataList(key_id);



    string strHTML = this.ControllerContext.ViewToString("Sample_ExcelDownload", this.ViewData, this.TempData, model);
    string filename = "excel_download_sample.xls";
    strHTML.ToExcelDownload(filename);

    return View();
}

 

 

View 내용인데, 일반적으로 사용하는 View 와 동일하다.

다만 Excel 파일로 열어줘야 하기 때문에 엑셀에서 인식하도록 몇가지 태그가 추가되었을 뿐이다.

 

 // 엑셀 내용에 대한 뷰 - Sample_ExcelDownload
@model HD.DataFactory.MySampleDataContainer
@{
    ViewBag.Title = "Excel";
    Layout = "~/Views/Shared/_ContentLayout.cshtml";
}

<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
<head>
    <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    <!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>sheet name</x:Name>
<x:WorksheetOptions>
<x:DisplayGridlines/>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>

<table class="doc_data_list" border="1">
...
</table>

</body>
</html>

 

 

Posted by 헝개