티스토리 뷰

아래 코드를 작성하면.

ASP.NET 에서 파일을 다운로드하게 할때.

SaveFileDialog(세이브파일다이얼로드) 창을 띄우게한다.



어떤 경우에 쓰느냐??


Excel.dll 파일을 이용해서 파일을 SaveAs 할때 다이얼로드창을 띄워서 다운로드 경로를 사용자가 설정하게 해주고싶을때. 

wBook은 WorkBook Calss 이다.

  wBook.SaveAs(strFileName, XlFileFormat.xlWorkbookNormal,

              System.Reflection.Missing.Value, System.Reflection.Missing.Value,

              false, false, XlSaveAsAccessMode.xlShared,

              XlSaveConflictResolution.xlLocalSessionChanges, false,

              System.Reflection.Missing.Value, System.Reflection.Missing.Value, false);

위 SaveAs 상태로 실행하면. strFileName 경로에만 저장된다.

즉 사용자가 원하는곳에 다운로드 시키지 못한다는것.

아래와 같은 코드를 넣어서 수정해주면 된다.



윈폼에서는 SaveFileDialog 를 쓰면 잘되지만.

ASP.NET 에서는 먹히질 않는다. 위에 wBook 코드 아래에 아래코드를 입력하면 자동으로 파일저장여부를 물으며 SaveFileDialog 창이 뜬다. 



string filepath = strFileName + ".xls";

            HttpContext.Current.Response.ContentType = "application/octet-stream";

            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "ExcelFile.xls");

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.WriteFile(filepath);

            HttpContext.Current.Response.End();



Result : 완성된 소스를 보면

String strFileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "ExcelFile";

wBook.SaveAs(strFileName, XlFileFormat.xlWorkbookNormal,

              System.Reflection.Missing.Value, System.Reflection.Missing.Value,

              false, false, XlSaveAsAccessMode.xlShared,

              XlSaveConflictResolution.xlLocalSessionChanges, false,

              System.Reflection.Missing.Value, System.Reflection.Missing.Value, false);



  if (excel != null)

            {

                excel.DisplayAlerts = false;

                wBook.Close();

                excel.Quit(); 

                Marshal.ReleaseComObject(excel);

                Marshal.ReleaseComObject(wSheet);

                Marshal.ReleaseComObject(wBook);

                Marshal.ReleaseComObject(oRang);

            }

SaveAs하고 꼭 마샬링 해줘야. Excel 사라진다. 안그러면 안사라짐.



string filepath = strFileName + ".xls";

            HttpContext.Current.Response.ContentType = "application/octet-stream";

            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "ExcelFile.xls");

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.WriteFile(filepath);

            HttpContext.Current.Response.End();
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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
글 보관함