'엑셀 내려받기'에 해당되는 글 1건

  1. 2016.07.20 ASP.NET MVC 에서 ViewEngine을 이용한 엑셀다운로드 방법
개발팁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 헝개