2013-04-24 3 views
2

데이터를 Excel 파일로 내보내는 웹 페이지가 있습니다. 내가 겪고있는 유일한 문제는 엑셀 파일을 열려고 할 때 "당신이 열려고하는 파일이 파일 확장명이 아닌 다른 형식입니다. 파일이 손상되지 않았으며 파일을 열기 전에 신뢰할 수있는 원본을 선택하십시오. " 어떻게이 메시지를 없앨 수 있습니까? 내보내기를 수행하려면 다른 기사에서 찾은 기능을 사용하고 있습니다. 코드는 다음과 같습니다.DataTable을 Excel로 내보내기 asp

private void ExporttoExcel(DataTable table) 
{ 
    //Response.Clear(); 
    HttpContext.Current.Response.Clear(); 
    HttpContext.Current.Response.ClearContent(); 
    HttpContext.Current.Response.ClearHeaders(); 
    HttpContext.Current.Response.Buffer = true; 
    HttpContext.Current.Response.ContentType = "application/excel"; 
    HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">"); 
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=TestingReports"); 
    HttpContext.Current.Response.Charset = "UTF-8"; 
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1252"); 
    // Sets font 
    HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>"); 
    HttpContext.Current.Response.Write("<BR><BR><BR>"); 
    // Sets the table border, cell spacing, border color, font of the text, background, foreground, font height 
    HttpContext.Current.Response.Write("<Table bgColor='#ffffff' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>"); 
    // Am getting my grid's column headers 
    int columnscount = table.Columns.Count; 

    // Write in new column 
    for (int j = 0; j < columnscount; j++) 
    { 
     HttpContext.Current.Response.Write("<Td style='font-size:15.0pt; text-align:center; width:80.0pt; border-width:1.0pt; border-color:#000000; border-style:solid; height:22.0pt;'>"); 
     // Get column headers and make it as bold in excel columns 
     HttpContext.Current.Response.Write("<B>"); 
     HttpContext.Current.Response.Write(table.Columns[j].ToString()); 
     HttpContext.Current.Response.Write("</B>"); 
     HttpContext.Current.Response.Write("</Td>"); 
    } 
    HttpContext.Current.Response.Write("</TR>"); 

    // Write in new row 
    foreach (DataRow row in table.Rows) 
    { 
     HttpContext.Current.Response.Write("<TR>"); 
     for (int i = 0; i < table.Columns.Count; i++) 
     { 
      HttpContext.Current.Response.Write("<Td style='width:80.0pt; text-align:center; border-width:0.5pt; border-color:#000000; border-style:solid; height:22.0pt;'>"); 
      HttpContext.Current.Response.Write(row[i].ToString()); 
      HttpContext.Current.Response.Write("</Td>"); 
     } 
     HttpContext.Current.Response.Write("</TR>"); 
    } 
    HttpContext.Current.Response.Write("</Table>"); 
    HttpContext.Current.Response.Write("</font>"); 
    HttpContext.Current.Response.Flush(); 
    HttpContext.Current.Response.End(); 

    //Response.Write("TestingReports.xls"); 
    //Response.Flush(); 
    //Response.End(); 
} 

도움이 될 것입니다. 미리 감사드립니다.

+0

중복입니다. 여기를 참고하십시오 http://stackoverflow.com/questions/3968973/how-can-i-write-data-into-an-excel-using-php –

답변

0

웹 사이트 할 수있다 파일이 Excel 2007에서 열리려고하면 다음과 같은 경고 메시지가 나타납니다.

"열려고하는 파일 '[filename]'의 형식이 파일 확장명이 아닌 다른 형식인지 확인하십시오. 파일을 열기 전에 신뢰할 수있는 원본의 파일입니다. 지금 파일을 열시겠습니까? " (예 | 아니오 | 도움말)

사용자가 예를 누르면 파일이 예상대로 열립니다. 사용자가 아니요를 클릭하면 파일이 열리고 두 번째 메시지가 표시 될 수 있으며 사용자가 아니요를 다시 선택하면 파일이 열리지 않습니다.

자세한 내용은 http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx

2

아래의 방법은 Excel에서 Excel로 내보내는 데 사용됩니다. 당신의 행함은 아마 그것은 또한 큰 파일에 매체에 읽을 수있는 시간이 오래 걸릴 것 일 것입니다 무슨 동안

// fileName = your file name like test.xls 
// dt = your data table 
// caption = it is caption which display on top of excel file. 


public static void Export(string fileName, DataTable dt, string Caption) 
     { 


      HttpContext.Current.Response.Clear(); 
      HttpContext.Current.Response.ClearHeaders(); 
      HttpContext.Current.Response.ClearContent(); 
      HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254"); 
      HttpContext.Current.Response.Charset = "windows-1254"; //ISO-8859-13 ISO-8859-9 windows-1254 

      HttpContext.Current.Response.AddHeader(
       "content-disposition", string.Format("attachment; filename={0}", fileName)); 
      HttpContext.Current.Response.ContentType = "application/ms-excel"; 
      string header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title></title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1254\" />\n<style>\n</style>\n</head>\n<body>\n"; 

      using (StringWriter sw = new StringWriter()) 
      { 
       using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 
       { 
        // Create a form to contain the grid 

        Table table = new Table(); 
        table.GridLines = GridLines.Horizontal; 
        //table.CellSpacing = 17;          

        if (Caption.Trim() != "") 
         table.Caption = "<span style='background-color: #FFFFFF; color: #666666; font-size: 14pt; font-weight: bold; padding: 5px 0px; height: 30px;'>" + Caption + "</span>"; 

        TableRow row = null; 
        row = new TableRow(); 
        for (int i = 0; i < dt.Columns.Count; i++) 
        { 
         TableHeaderCell headerCell = new TableHeaderCell(); 
         headerCell.Text = dt.Columns[i].ColumnName; 
         PrepareControlForExport(headerCell); 
         row.Cells.Add(headerCell); 
        } 
        table.Rows.Add(row); 
        foreach (DataRow rows in dt.Rows) 
        { 
         row = new TableRow(); 
         for (int i = 0; i < dt.Columns.Count; i++) 
         { 
          TableCell RowCell = new TableCell(); 
          RowCell.Text = rows[i].ToString(); 
          PrepareControlForExport(RowCell); 
          row.Cells.Add(RowCell); 
         } 
         table.Rows.Add(row); 
        } 

        // render the table into the htmlwriter 
        table.RenderControl(htw); 

        // render the htmlwriter into the response 
        HttpContext.Current.Response.ContentType = "text/csv"; 
        HttpContext.Current.Response.Write(header + sw.ToString()); 
        HttpContext.Current.Response.End(); 

       } 
      } 
     } 

     private static void PrepareControlForExport(Control control) 
     { 
      for (int i = 0; i < control.Controls.Count; i++) 
      { 
       Control current = control.Controls[i]; 
       if (current is LinkButton) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); 
       } 
       else if (current is ImageButton) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); 
       } 
       else if (current is HyperLink) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); 
       } 
       else if (current is DropDownList) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); 
       } 
       else if (current is CheckBox) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); 
       } 
       else if (current is Label) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as Label).Text)); 
       } 

       if (current.HasControls()) 
       { 
        ReportExport.PrepareControlForExport(current); 
       } 
      } 
     } 
0

. 당신이 데이터 집합을 가지고 있기 때문에 당신이해야 할 모든 루프는 파일 스트림을 만드는 과정이며

1

application/ms-excel에 콘텐츠 형식을 변경하여 엑셀 문서가 파일 이름에 확장자 포함됩니다 this excel reader out.을 확인합니다. 즉

Response.ContentType = "application/ms-excel"; 
Response.AppendHeader("Content-Disposition", "attachment;filename=MyFileName.xls"); 

나는 이것에 관해서 3 가지 다른 방법으로 article을 작성했습니다. 이러한 방법 중 하나를 사용할 수 있습니다.

HTML 테이블 방법 : Microsoft Excel에서 내부 웹 페이지의 콘텐츠를 엽니 다 "응용 프로그램/X-msexcel"또는 "응용 프로그램/vnd.ms-엑셀"MIME 형식을 사용

public void ExportToExcel(DataTable table) 
    { 
     HttpContext context = HttpContext.Current; 
     context.Response.Clear(); 

     //Begin Table 
     context.Response.Write("<table><tr>"); 

     //Write Header 
     foreach (DataColumn column in table.Columns) 
     { 
      context.Response.Write("<th>" + column.ColumnName + "</th>"); 
     } 
     context.Response.Write("</tr>"); 

     //Write Data 
     foreach (DataRow row in table.Rows) 
     { 
      context.Response.Write("<tr>"); 
      for (int i = 0; i < table.Columns.Count; i++) 
      { 
       context.Response.Write("<td>" + row[i].ToString().Replace(",", string.Empty) + "</td>"); 
      } 
      context.Response.Write("</tr>"); 
     } 

     //End Table 
     context.Response.Write("</table>"); 

     context.Response.ContentType = "application/ms-excel"; 
     context.Response.AppendHeader("Content-Disposition", "attachment;filename=MyFileName.xls"); 
     context.Response.End(); 
    }