2015-04-30 62 views
1

我正在使用Epplus將數據表寫入excel文件,它工作正常。我該如何做直放站?直放站數據使用Epplus優秀?

 using (ExcelPackage pck = new ExcelPackage()) 
     { 
      ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo"); 
      ws.Cells["A1"].LoadFromDataTable(dt, true); 
      Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
      Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx"); 
      Response.BinaryWrite(pck.GetAsByteArray()); 
     } 

回答

1

中繼器類有一個屬性Data,所以你必須分配你的數據表。代碼可能類似於以下

repeater.DataSource = dt; //dt variable is same as in your example 
    repeater.DataBind(); 

關於爲什麼DataBind是必要的,你可以閱讀:Why is the DataBind() method necessary?

+0

NOTE:事實上,我得到的數據表,然後將它們存儲到類對象,然後該項目結合這就是爲什麼我不能夠使用中繼器它操作爲不同的格式「LoadFromDatatable」選項Epplus。 – siddhipur

+0

@siddhipur爲什麼你的問題中的例子使用這個功能? –

+0

無論如何,如果它的類對象看這裏http://stackoverflow.com/questions/674204/binding-a-generic-list-to-a-repeater-asp-net –

1

當你說成「類對象」我想你的意思是對象的集合?如果你綁定到一箇中繼器,這將是有意義的。如果是這樣,爲什麼不使用LoadFromCollection呢?就像這樣:

[TestMethod] 
public void LoadFromCollection_Test() 
{ 
    //http://stackoverflow.com/questions/29958463/repeater-data-to-excel-using-epplus 
    //Throw in some data 
    var dataSet = new List<RowObject>(); 
    for (var a = 0; a < 20; a++) 
     dataSet.Add(new RowObject 
     { 
      ColumnString = "Row " + a, 
      ColumnDateTime = DateTime.Now.AddHours(a) 
     }); 

    //Clear the file 
    var newFile = new FileInfo(@"C:\Temp\Temp.xlsx"); 
    if (newFile.Exists) 
     newFile.Delete(); 

    var i = 0; 
    using (var package = new ExcelPackage(newFile)) 
    { 
     var ws = package.Workbook.Worksheets.Add("Sheet1"); 
     ws.Cells["A1"].LoadFromCollection(dataSet, true); 

     package.Save(); 
    } 
} 

public class RowObject 
{ 
    public string ColumnString { get; set; } 
    public DateTime ColumnDateTime { get; set; } 
}