2013-11-03 34 views
0

我有一個包含一些數據的列表數組。目前我可以在控制檯中看到輸出,現在試圖添加到excel文件中。任何人都可以解釋我該怎麼做。這裏是創建Excel表格並寫入內容的代碼。但是,如何結合這兩個代碼來查看excel中的輸出。我嘗試了幾種組合,但無法寫入excel。我是c#的新手。提前感謝!如何將列表數組寫入Excel文件

foreach (Match m in linkParser.Matches(html)) 
       { 
       list.Add(m.Value); 
       Console.WriteLine(m.Value); 
       } 



    Excel.Application oApp; // to open excel 
       Excel.Worksheet oSheet; 
       Excel.Workbook oBook; 
       oApp = new Excel.Application(); 
       oBook = oApp.Workbooks.Add(); 
       oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1); 
       string fileTest = "output123.xlsx"; 
       if (File.Exists(fileTest)) 
       { 
        File.Delete(fileTest); 
       } 


       oSheet.Cells[1, 1] = "some value"; 

       oBook.SaveAs(fileTest); 
       oBook.Close(); 
       oApp.Quit(); 
+0

有很多庫可以在[這個老問題]中做到這一點(http://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c-sharp?rq=1 )。你也可以通過編寫HTML並將它稱爲.xls來破解一些東西,但它不是一個真正的Excel文件。 – Rup

+0

一種可能性是自動化Office產品[使用主互操作程序集 - PIA](http://msdn.microsoft.com/en-us/library/dww0e04a%28v=vs.90%29.aspx)。使用PIA創建一個excel實例,通過它打開/創建一個工作簿,用數據填充工作表,保存並關閉excel實例。 – pasty

回答

2

互操作,單元 - 有點開銷。創建一個空的工作簿並將其保存爲二進制資源。無論何時您需要創建一個新文件,只需抓住該資源並寫入磁盤即可。然後使用Microsoft.Ace.OleDb.<version>連接到此Excel文件。您可以像寫入數據庫表一樣寫入它。這裏是解釋關於這個問題的

http://yoursandmyideas.wordpress.com/2011/02/05/how-to-read-or-write-excel-file-using-ace-oledb-data-provider/

看到,隨着interop,特別是如果你寫的服務器端應用程序的好文章,它是沒有效率做new Excel.Application() - 你從字面上打開Excel程序。您不想在服務器上打開任何Office program,除非服務器專用於此服務器,並且您有邏輯可以從卡住的內存中恢復內存Office App。使用ACE,您只需打開一個連接 - 非常簡單,高效的內存方法。

0

包括在你的參考的Excel互操作。這裏有一些快速和髒的代碼。請註明您所使用的框架,一些新的語法已經在4.0版中添加,不會對V3.5

using Excel = Microsoft.Office.Interop.Excel; 

工作現在寫下面的代碼創建Excel的應用程序。

Excel.Application excel = new Excel.Application(); 
    excel.Visible = true; 
    Excel.Workbook wb = excel.Workbooks.Add(); 
    Excel.Worksheet sh = wb.Sheets.Add(); 
    sh.Name = "TestSheet"; 

    // Write some kind of loop to write your values in sheet. Here i am adding values in 1st columns 
    for (int i = 0; i < list.Count; i++) 
    { 
     sh.Cells[i.ToString(), "A"].Value2 = list[i]; 

    } 
    string filePath = @"C:\output123.xlsx"; 

    // Save file to filePath 
    wb.Save(filePath); 

    wb.Close(true); 
    excel.Quit(); 

** PS-我沒有測試過代碼,但你應該可以通過一些小小的調整來運行它。