티스토리 뷰

 

 

 ASP.NET에서 MSSQL, MySQL 등 DB를 통하여 글 목록과 게시글을 표시하는데 목록 유형에 따라 해당 목록을 CSV 파일로 저장할 필요가 있어서 관련 레퍼런스를 검색해봤다.

 

 

JavaScript에서 CSV 파일 생성

 

개발 초기에는 디자이너 코드에서 버튼 클릭 후 JavaScript를 통해 CSV 파일을 생성하는 방식으로 진행했습니다.

아래 링크에서 확인된 코드를 적용하였고 DB에 데이터를 불러와 <table> 안에 추출할 목록을 완성한 후 <table> 태그 Id와 추출 filename을 매개변수로 넣어주면 row와 col을 조회하면서 ',' 구분자로 CSV 형식의 파일이 생성됩니다.

 

stackoverflow.com/a/24922761

 

How to export JavaScript array info to csv (on client side)?

I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which looks like this: [["name1", "city_name1...

stackoverflow.com

function exportTableToCSV($table, filename) {

            var $rows = $table.find('tr:has(td),tr:has(th)'),
                
                tmpColDelim = String.fromCharCode(11), 
                tmpRowDelim = String.fromCharCode(0), 

                colDelim = '","',
                rowDelim = '"\r\n"',

                csv = '"' + $rows.map(function (i, row) {
                    var $row = jQuery(row), $cols = $row.find('td,th');

                    return $cols.map(function (j, col) {

                        var $col = jQuery(col), text = $col.text();
                        return text.replace(/"/g, '""');

                    }).get().join(tmpColDelim);

                }).get().join(tmpRowDelim)
                    .split(tmpRowDelim).join(rowDelim)
                    .split(tmpColDelim).join(colDelim) + '"',

                csvData = 'data:application/csv;charset=UTF-8' + encodeURIComponent(csv);

            if (false && window.navigator.msSaveBlob) {
                var blob = new Blob(["\ufeff", decodeURIComponent(csv)], {
                    type: 'text/csv;charset=UTF-8'
                });

                window.navigator.msSaveBlob(blob, filename);

            }
            else if (window.Blob && window.URL) {     
                var blob = new Blob(["\ufeff", csv], {
                    type: 'text/csv;charset=UTF-8'
                });
                var csvUrl = URL.createObjectURL(blob);

                $(this)
                .attr({
                    'download': filename,
                    'href': csvUrl
                });
            }
            else {
                var csvData = 'data:application/csv;charset=UTF-8' + encodeURIComponent(csv);

                $(this)
                .attr({
                    'download': filename,
                    'href': csvData,
                    'target': '_blank'
                });
            }
        }

 

 

ASP.NET C# 코드를 통해 CSV 파일 생성 방법

 

하지만 위 방법에서 Chrome 브라우저는 문제없이 파일이 생성되지만 IE 브라우저에서는 버전 차이 때문인지 파일 접근 허용 박스가 표시되면서 작동되지 않는 현상이 발생했습니다. 

 

원인 파악이 빨리 이루어지지 않아서 다른 방법을 찾아서 적용하였습니다.

 

csvPage.aspx

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
</head>
<body>
    <form id="form1" runat="server">
        <div>             
        </div>
    </form>
</body>
</html>

csvPage.aspx.cs

	protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Response.Clear();
                Response.ContentType = "application/CSV";

                Response.Charset = "utf-8";
                Session.CodePage = 65001;
                
                // attachment 넣으면 다운로드됨
                Response.AddHeader("Content-Disposition", "attachment; filename=" + "exportFileName" + ".csv");
                WriteCsv(Request["userName"], Request["date"]);

                Response.Flush();
                Response.SuppressContent = true;
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        } 
        
        
        public void WriteCsv(string userName, string date)
        {
            DataTable dt = new DataTable();

			//DataTable에 전달 받은 매개변수를 통해 추출할 목록을 DB에서 가져온다.
            dt = GetTableList(string userName, string date);
            
            if (dt != null)
            {
                //헤더라인
                Response.Write(string.Format("{0},{1},{2},{3}", "아이디", "글제목", "이름", "생성일"));
                Response.Write(Environment.NewLine);

				//내용
                foreach (DataRow row in dt.Rows)
                {                    
                    foreach (DataColumn col in dt.Columns)
                    {
                        Response.Write(Convert.ToString(row[col]).Replace(",", "\",\"") + ",");
                    }
                    Response.Write(Environment.NewLine);
                }
            }
        }

 

다운로드할 페이지에서 다운로드 버튼을 클릭했을 때

window.location = 'csvPage.aspx?userNaem=param1&date=param2'로 변수를 전달하고 위 페이지로 받게 되면 

보일 때는 페이지 전환 없이 다운로드를 진행합니다.

 

 

 

마무리..

 C# 비하인드 코드로 CSV 파일을 다운하는 방법을 알아보았습니다.

 

 - Response 파일 추출 공부 후 추가 정리 필요..

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함