2008-09-29 4 views
5

에서 Excel로 쿼리 결과 보내기 사용자가 웹 사이트에서 임시 쿼리를 만들도록합니다. 사용자가 기준을 선택한 다음 제출을 클릭하고 결과가 자동으로 Excel로 스트리밍되게하십시오. 응용 프로그램에서 DataTable을 채운 다음 데이터 테이블을 사용하여 탭으로 구분 된 문자열을 만듭니다. 문제는 그것을 얻는 것입니다.ASP.NET 웹 사이트

데이터를 Excel로 스트리밍하는 가장 좋은 방법은 무엇입니까? 우리는 사용자가 제출 버튼을 클릭 한 후 빈 창을 닫을 필요가 없도록하는 것이 바람직합니다.

답변

10

페이지의 파일 형식을 Excel로 변경하고 페이지를 구성하는 데 필요한 HTML 만 스트리밍하십시오. here

//for demo purpose, lets create a small datatable & populate it with dummy data 
System.Data.DataTable workTable = new System.Data.DataTable(); 

//The tablename specified here will be set as the worksheet name of the generated Excel file. 
workTable.TableName = "Customers"; 
workTable.Columns.Add("Id"); 
workTable.Columns.Add("Name"); 
System.Data.DataRow workRow; 

for (int i = 0; i <= 9; i++) 
{ 
workRow = workTable.NewRow(); 
workRow[0] = i; 
workRow[1] = "CustName" + i.ToString(); 
workTable.Rows.Add(workRow); 
} 

//...and lets put DataTable2ExcelString to work 
string strBody = DataTable2ExcelString(workTable); 

Response.AppendHeader("Content-Type", "application/vnd.ms-excel"); 
Response.AppendHeader("Content-disposition", "attachment; filename=my.xls"); 
Response.Write(strBody); 
+1

Excel을 열고 수동으로 생성 한 것처럼 정상적인 Excel 파일을 생성하지 않는다는 사실을 명심하십시오.이 파일은 html 파일입니다. –

0

의 코드는 내가 유일한 문제는 DataTable의에서 엑셀 파일을 생성하는 filehandler (.ashx) 사용하는 것이 좋습니다 것입니다. 이 작업을 수행 할 타사 제품이 많이 있습니다 (예 : Infragistics는 이러한 기능을 수행하는 구성 요소를 제공합니다).

내가 추천하는 한 가지는 서버에서 Excel interop을 사용하는 것입니다 ... 매우 중량이며 지원되지 않습니다.

1

결과가있는 테이블 인 페이지를 만들고 페이지의 콘텐츠 형식을 "application/vnd.ms-excel"로 설정하면 출력이 Excel로 표시됩니다.

Response.AddHeader("Content-Disposition", "attachment; filename=somefilename.xls"); 
0

당신은 당신의 데이터 집합을 한 후에는 객체로 변환 할 수 있습니다 [,]와에 삽입 : 당신이 저장 강제하려면

Response.ContentType = "application/vnd.ms-excel"; 

, 당신은 다음과 같은 일을 할 것입니다 Excel 문서. 그런 다음 문서를 디스크에 저장하고 사용자에게 스트리밍 할 수 있습니다.

 //write the column headers 
     for (int cIndex = 1; cIndex < 1 + columns; cIndex++) 
      sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption); 
     if (rows > 0) 
     { 

      //select the range where the data will be pasted 
      Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]); 

      //Convert the datatable to an object array 
      object[,] workingValues = new object[rows, columns]; 

      for (int rIndex = 0; rIndex < rows; rIndex++) 
       for (int cIndex = 0; cIndex < columns; cIndex++) 
        workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString(); 

      r.Value2 = workingValues; 
     } 
+0

하지만 서버에서 Excel을 자동화하지 마십시오. http://support.microsoft.com/kb/257757 – Cheeso

+0

이것은 클라이언트 측에서 수행되었습니다. –

0

DataTable을 네이티브 xls 형식으로 변환하기 위해 .xls 파일 확장명에 대한 처리기와 무료 구성 요소를 사용합니다. 이 사이트의 구성 요소 http://www.csvreader.com/은 URL이 의미하는 것 이상을 수행합니다. 엑셀의 최신 버전은 HTML 형식의 XLS 파일에 대해 불평 할 것입니다. 또한 반환되는 데이터의 크기를 기억하십시오. 웹 서버는이 확장에 압축을 사용해야하며 리턴 된 행 수가 하나의 워크 시트에 표시 할 수있는 것보다 큰지 확인해야합니다. 여러 장이 필요할 수 있습니다. http://www.mrexcel.com/archive2/23600/26869.htm

1

이미이 작업을 수행하는 유틸리티 기능이 있습니다. 당신은 데이터 테이블에 넣어하면이 문제를 해결할 수

 public static void DataTabletoXLS(DataTable DT, string fileName) 
    { 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.Charset = "utf-16"; 
     HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250"); 
     HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName)); 
     HttpContext.Current.Response.ContentType = "application/ms-excel"; 

     string tab = ""; 
     foreach (DataColumn dc in DT.Columns) 
     { 
      HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", "")); 
      tab = "\t"; 
     } 
     HttpContext.Current.Response.Write("\n"); 

     int i; 
     foreach (DataRow dr in DT.Rows) 
     { 
      tab = ""; 
      for (i = 0; i < DT.Columns.Count; i++) 
      { 
       HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", "")); 
       tab = "\t"; 
      } 
      HttpContext.Current.Response.Write("\n"); 
     } 
     HttpContext.Current.Response.End(); 
       } 
+0

+1. 그럼에도 불구하고, 여러 개의 결과 세트를 반환하고, 기존 Excel 템플릿을 사용하고, 여러 워크 시트를 만들고, 각 워크 시트를 적절한 워크 시트의 해당 셀에 배치 할 수 있습니까? – mg1075

0

이 친절 format.Hope을 텍스트로 엑셀 시트를 변환됩니다 problem.This 코드를 해결하려면이 코드를 사용하여 응답으로 내보낼 수 있습니다

grdSrcRequestExport.RenderControl(oHtmlTextWriter); 
    string s = ""; 
    s=oStringWriter.ToString().Replace("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">", ""); 
    s="<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=us-ascii\"><meta name=ProgId content=Excel.Sheet><meta name=Generator content=\"Microsoft Excel 11\"><table x:str border=0 cellpadding=0 cellspacing=0 width=560 style='border-collapse: collapse;table-layout:fixed;width:420pt'>"+s.ToString()+"</table></body></html>"; 
    //Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes(); 
    Response.Write(s);