다음 코드는 몇 달 전에 작성되었으며 Excel에서 재미있는 작은 경고 메시지와 함께 완벽하게 테스트되었습니다. 이제 C# 코드가 오류없이 실행되고 브라우저에서 내 보낸 .xls 파일을 다운로드하면 Excel 응용 프로그램이 열리고 내 보낸 파일을 열지 않은 것처럼 아무 것도 표시하지 않습니다. 누구든지이 코드의 문제점을 보거나 Excel이 갑자기이 문서를 열지 않는 이유를 알 수 있습니까? 미리 많은 감사드립니다!Excel에서 C# StringBuilder로 만든 .xls를 열지 않았습니다.
C# 코드 :
[HttpGet]
public void DownloadReport()
{
string filename = "ReportExport";
//Report source data organized here
StringBuilder sb = new StringBuilder();
sb.Append("<table>");
sb.Append("<tr>");
foreach (DataColumn column in reportData.Columns)
{
sb.Append("<th>");
sb.Append(column.ColumnName);
sb.Append("</th>");
}
sb.Append("</tr>");
foreach (DataRow row in reportData.Rows)
{
sb.Append("<tr>");
foreach (DataColumn column in reportData.Columns)
{
sb.Append("<td>");
if (row[column] == null)
{
sb.Append("");
}
else
{
sb.Append(row[column]);
}
sb.Append("</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
string style = @"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
XLS 파일을 생성하지 않습니다. 명시된 코드는 HTML 조각을 생성하고 브라우저에 Excel 파일임을 알립니다. Excel 자체가 데이터를 검사하여 파싱 할 수 없습니다 (바이너리 데이터가 필요함). Excel 생성기 라이브러리를 사용하는 것이 더 좋습니다. –
@rboe - 응답 해 주셔서 감사합니다. 이 코드는 이전에 Excel 파일을 생성했으며 여기에 설명 된 원칙을 기반으로합니다. http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c -sharp.html. 문제는 이전에 작동하고 갑자기 작동을 멈추게하는 이유입니다. – jle
이 방법은 Excel이 자동으로 다른 형식 (이 경우 HTML로 텍스트)을 자동으로 검색하는 기능에 의존합니다. 나는이 자동 발견 기능이 시간이 지남에 따라 행동을 변화시키지 않는다는 것에 의존하지 않을 것이다. –