2017-09-27 6 views
0

에서 C# 내보내기 데이터를 사용하여 Excel을 사용하고 있습니다. 이것은 처음에는 잘 작동합니다. 사용자가 행의 동일한 페이지에서 여러 개의 내보내기를 요청하면 "파일을 읽을 수 없음"이라는 오류 메시지를 받기 시작하여 버튼 이벤트를 통해 내보내기가 트리거됩니다. "SAVE"파일을 열기 대신 선택하면 파일을 잘 작성합니다. 브라우저에서 파일을 열지 않습니다.Excel로 내보낼 때 파일을 읽을 수 없습니다. C#

Excel이 열리지 만 내 파일을로드하지 않기 때문에 Excel에서 오류가 발생한다는 것은 확실합니다.

나는 Response.End와 Response.Close에 대해 읽었습니다. 어떤 사람들은 결코 그것들을 사용한다고 말하지 않습니다. 나는 끝과 끝의 모든 조합을 시도했다.

내 브라우저가 닫히거나 (또는 ​​오랜 시간 기다려야하기 때문에) 문제가 해결되기 때문에 뭔가가 메모리에 캐시되고 있다는 느낌을 받았습니다.

누군가가 잘못 될 수 있다는 생각을 갖고 있습니까? 아니면 문제없이 하드 드라이브에서 파일을 읽고 쓸 수있을 때 Excel이 내 파일을 읽을 수없는 이유를 어떻게 알 수 있습니까?

 protected void btnSaveToXls_Click(object sender, EventArgs e) 
{ 

    Response.ClearHeaders(); 
    Response.Cache.SetCacheability(HttpCacheability.Private); 
    Response.Buffer = true; 
    Response.AddHeader("content-transfer-encoding", "binary"); 
    Response.Clear();   
    Response.AddHeader("Content-Disposition", "attachment; filename=myFileName.xls"); 
    Response.AddHeader("pragma", "private"); 
    Response.ContentType = "application/vnd.ms-excel"; 

    using (StringWriter sw = new StringWriter()) 
    { 
     // The main purpose of these next two writes are to name the worksheet and add the gridlines to the excel sheet 
     sw.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">"); 
     sw.Write(@"<head> 
       <xml> 
       <x:ExcelWorkbook> 
        <x:ExcelWorksheets> 
         <x:ExcelWorksheet> 
          <x:Name>Clients Contacted</x:Name> 
          <x:WorksheetOptions> 
           <x:Panes></x:Panes> 
           <x:Print><x:Gridlines /></x:Print> 
          </x:WorksheetOptions> 
         </x:ExcelWorksheet> 
        </x:ExcelWorksheets> 
       </x:ExcelWorkbook> 
       </xml> 
      </head>"); 

     using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 
     { 
      Label newLine = new Label(); 
      newLine.Text = "<br/>"; 
      GridView gv = new GridView(); 
      gv.GridLines = GridLines.Both; 
      gv.HeaderStyle.Font.Bold = true; 

      //. . . 
      // a bunch of code here to populate my gridview 
      //. . . 

      Panel p = new Panel(); 
      p.Controls.Add(lblTitle); 
      p.Controls.Add(new Label { Text = "<BR/>" }); 
      p.Controls.Add(lblReportTitle); 
      p.Controls.Add(new Label { Text = "<BR/>" }); 
      p.Controls.Add(new Label { Text = string.Format("Run Date {0}", DateTime.Now.ToString("MM/dd/yyyy")) }); 
      p.Controls.Add(new Label { Text = "<BR/>" }); 
      p.Controls.Add(new Label { Text = "<BR/>" }); 
      p.Controls.Add(gv); 

      p.RenderControl(htw); 
      try 
      { 
       // Response.Clear(); 
       sw.Write("</html>"); 
       Response.Buffer = true; 
       Response.Output.Write(sw.ToString()); 
       // Response.Output.Flush(); 
       Response.Flush(); 
       // Response.End(); 
      } 
      catch (Exception ex) 
      { 
       //... Logging the error ... 
      } 
      finally 
      { 
       Response.Close(); 
      } 
     } 
    } 
} 
+1

첨부 파일을 올바르게 형식화해야합니다. 예를 들어 string.Format 함수를 먼저 사용하지 않고이 구문 스타일을 사용하여 작동 시키십시오. 'Response.AddHeader "Content-Disposition", "attachment; 파일 이름 = myFileName.xls" – MethodMan

+0

@MethodMan 확인. 나는 당신의 제안을 받아 내 모범을 보였습니다. 전에 예제를 더 짧게 만들고 보안상의 이유로 비트를 잘라 내기 전에. 업데이트 된 코드는 여전히 동일한 문제가 있습니다. – rnesolydev

답변

0

다음은 내가 알아 낸 것입니다. 이 문제는 두 번째로 대화 상자가 I.E.에서 기다릴 필요가있는 것으로 보입니다. ("열기", "저장"또는 "취소")를 눌러 배경색을 변경하십시오. 제 경우에는 흰색 배경에서 노란색 배경으로 바뀌 었습니다. 내 생각 엔 Excel이 문서를 열려고 시도하기 전에 문서가 클라이언트에 다운로드 된 것이 아닙니다. Chrome이 너무 빠르면 오류가 발생했지만 어쨌든 열었습니다. 파일이 정상적으로 보입니다.