2016-08-03 108 views
0

我想使用List添加標題列。EPPlus Excel導出,如何從列表中打印標題列

我試過這個,但它只打印第一列。

List<string> headerColumns1 = new List<string>() 
{ 
    "1", 
    "2", 
    "3" 
}; 

ExcelPackage excel = new ExcelPackage(); 
var workSheet = excel.Workbook.Worksheets.Add("Sheet1"); 
workSheet.Cells[1, 1].LoadFromCollection(headerColumns, false); // 
workSheet.Cells[2, 1].LoadFromCollection(data, false); 

它只在第一列中打印「1」。

如何在第一行打印所有標題列?

+0

我可以做這與Microsoft.Interop.Excel通過使用工作表的範圍 – Forlani

+0

@Forlani不這樣做。在服務器的情況下,它需要安裝MS Office。 EPPlus功能非常強大的庫。 – SouXin

+0

@SouXin我會看看它。謝謝 – Forlani

回答

1

您只指定了一個細胞 此代碼:workSheet.Cells[1, 1]顯示你的錯誤

你有兩個選擇: 指定範圍

using (ExcelRange range = ec.Cells[1, 1, 1, headerColumns.Count]) 
{ 
    range.LoadFromCollection(headerColumns, false); 
} 

或者使用的foreach來填充手動

int index = 1; 
foreach(var item in headerColumns) 
{ 
    workSheet.Cells[1, index++].Value = item; 
} 

看看LoadFromCollection

Load a collection into a the worksheet starting from the top left row of the range.

p.s.我相信這只是輸入錯誤:List<string> headerColumns1 = new List<string>()針對workSheet.Cells[1, 1].LoadFromCollection(headerColumns, false);

0

函數將採用一個集合並將每個條目視爲對象,並使用Reflections將每個屬性打印爲列值。所以如果你給它的集合,它看到它R1C1 =「1」,R2C1 =「2」,然後R3C1 =「3」。

,但workSheet.Cells[2, 1].LoadFromCollection(data, false);它將覆蓋從R2C1所有值和向下,因爲這是它開始在右上角的電池就行了。

所以,做你想做的,你需要給的東西用List一個單一的條目。例如,這將解決以上代碼中的問題(但你可能最終需要一些更復雜的再Tuple):

var headerColumns = new List<Tuple<string, string, string>> 
{ 
    new Tuple<string, string, string>("1","2","3") 
}; 

workSheet.Cells[1, 1].LoadFromCollection(headerColumns, false); 

這顯示了這一點:

enter image description here