데이터를 Excel 스프레드 시트로 내보내는 데 필요한 여러 페이지가 있습니다. Excel 파일을 생성 할 수는 있지만이 동작을 추상화하는 방법을 연구하여 필요한 모든 페이지에서 쉽게 재사용 할 수 있습니다. 이 코드는 인스턴스 방법으로 잘 작동정적 메서드에서 Response.TransmitFile() 호출
protected void lnkExport_Click(object sender, EventArgs e)
{
List<List<string>> dataList = GatherDataForSpreadsheet();
Utility.SendExcelFile(this, "fileNameForDownload.xlsx", dataList, "MyReports");
}
: 나는 SendExcelFile
를 호출하고있어
public static void SendExcelFile(System.Web.UI.Page callingPage, string downloadFileName, List<List<string>> data, string worksheetTitle)
{
string tempFileName = Path.GetTempFileName();
try
{
// Generate file using ExcelPackage
GenerateExcelDoc(tempFileName, data, worksheetTitle);
callingPage.Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
callingPage.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
callingPage.Response.AddHeader("Content-Length", new FileInfo(tempFileName).Length.ToString());
callingPage.Response.TransmitFile(tempFileName);
}
finally
{
//When this is removed, the method works as expected.
if (File.Exists(tempFileName))
File.Delete(tempFileName);
}
}
클릭 처리기는 다음과 같습니다 : 다음과 같이 나의 현재 생각은 정적 유틸리티 메소드를 사용하는 것입니다 호출 페이지의 그러나 정적 방법으로는 전혀 작동하지 않습니다. 이 버튼을 클릭하면 브라우저에 로딩 애니메이션이 무기한 표시되지만 파일 다운로드를 묻는 메시지는 표시되지 않습니다.
저는 ASP.NET (및 웹 프로그래밍 전반)에 매우 익숙하므로 여기에 뭔가 빠졌습니다. 누군가 내가 본 행동을 설명하고이 접근법에 대한 합리적인 대안을 제안 할 수 있습니까?
EDIT : 마지막에 File.Delete() 호출을 제거하면 메서드가 예상대로 작동합니다. Response.TransmitFile()은 전송을 비동기 적으로 수행합니까?
EDIT 2 : 파일을 삭제하기 전에 Response.Flush()를 호출해야했습니다. 아래 내 대답을 참조하십시오. 감사합니다.
public static void SendExcelFile(string downloadFileName, List<List<string>> data, string worksheetTitle)
{
var context = HttpContext.Current;
string tempFolder = context.Request.PhysicalApplicationPath + "temp";
string tempFileName = tempFolder + "tempFileName.xlsx"
if (!Directory.Exists(tempFolder))
Directory.CreateDirectory(tempFolder);
// Generate file using ExcelPackage
GenerateExcelDoc(tempFileName, data, worksheetTitle);
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("Content-Length", new FileInfo(tempFileName).Length.ToString());
context.Response.TransmitFile(tempFileName);
File.Delete(tempFileName);
}
또 다른 대안이 방법을 포함 페이지의 기본 클래스, 즉 훨씬 쉽게 경로 일 수 있습니다
코드를 디버그 모드로 이동 했습니까? 그렇다면 시간이 초과되는 부분 (또는이 방법으로 들어가는 경우)을 말할 수 있습니까? 'SendExcelFile' 메쏘드가 예외를 던지고 있습니까? 그렇다면 예외의 스택 추적을 추가하십시오. 그러면이 문제를 해결하는 데 도움이 될 것입니다. 아, 그리고이 메소드에 대한 샘플 호출도 도움이 될 것입니다 (아마도 클릭 핸들러). –
나는 그것을 통해 디버깅했습니다. SendExcelFile 메서드가 정상적으로 실행 된 다음 종료되지만 브라우저에서 파일 다운로드를 묻지 않습니다. IE 또는 Firefox의 탭에는로드 애니메이션이 표시되며 브라우저 하단에 페이지로드 진행률 표시 줄이 있습니다. 페이지 자체는 반응 적입니다. – Odrade
원하는 경우 클릭 처리기를 게시 할 수 있지만 도움이 될지 의심 스럽습니다. 간단히 말해서 다음과 같습니다. var data = GenerateData(); Utility.SendExcelFile (data); – Odrade