2012-03-05 12 views
4

Excelは読み取り不可能なデータがあることを教えています。したがって、情報を回復しようとすると、正しいデータが表示されます。しかし、xlsxのテキストファイルを開くと、単にgridview(Excelが話している読めないコンテンツです)ではなく、ページ全体のHTMLがすべて取得されます。ここでEPPlusを使用して、Excelシートにグリッドビューをエクスポートしようとしています

は私のコードです:起こっかもしれないものについて

public void ExcelDownload(object sender, EventArgs e) 
    { 
     DataSet _MailingListUsers = db.GetMailingList(); 
     DataTable mailTable = _MailingListUsers.Tables[0]; 

     DumpExcel(mailTable); 

    } 

    private void DumpExcel(DataTable tbl) 
    { 
     using (ExcelPackage pck = new ExcelPackage()) 
     { 
      //Create the worksheet 
      ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Mailing List"); 

      //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1 
      ws.Cells["A2"].LoadFromDataTable(tbl, false); 

      //Header Titles 
      ws.Cells["A1"].Value = "Employee Name"; 
      ws.Cells["B1"].Value = "Email Address"; 
      ws.Cells["C1"].Value = "Phone"; 
      ws.Cells["D1"].Value = "Business Unit"; 
      ws.Cells["E1"].Value = "Site"; 

      ws.Cells["A1"].AutoFitColumns(); 

      //Format the header for column 1-3 
      using (ExcelRange rng = ws.Cells["A1:E1"]) 
      { 
       rng.Style.Font.Bold = true; 
       //Set Pattern for the background to Solid 
       rng.Style.Fill.PatternType = ExcelFillStyle.Solid;  
       //Set color to dark blue 
       rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189)); 
       rng.Style.Font.Color.SetColor(System.Drawing.Color.White); 
      } 


      //Write it back to the client 
      Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
      Response.AddHeader("content-disposition", "attachment; filename=MailingList.xlsx"); 
      Response.BinaryWrite(pck.GetAsByteArray()); 
     } 
    } 

任意のアイデア?誰かがEPPlusを使って、HTMLデータをExcelに送信しようとして同じ問題が発生し、gridViewだけでなくページ全体を送信した後に提案しました。

おかげ

答えて

9
私は Response.Clear()Response.End()を欠けている

try { 
    var pck = new OfficeOpenXml.ExcelPackage(); 
    var ws = pck.Workbook.Worksheets.Add("Mailing List"); 
    ws.Cells["A2"].LoadFromDataTable(tbl, false); 
    Response.Clear(); 
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
    Response.AddHeader("content-disposition", "attachment; filename=MailingList.xlsx"); 
    Response.BinaryWrite(pck.GetAsByteArray()); 
} catch (Exception ex) { 
    //log error 
} 
Response.End(); 
+1

グレート!それはうまくいった!ありがとう。 – shawleigh17

+0

ベストソリューション............................................... ........... !!! :D – Butters

+0

私はちょうど4行目がこのようなものでなければならないことを指摘したい: ws.Cells ["A2"]。LoadFromDataTable(tbl、false); –

関連する問題