如何将列表数组写入Excel文件

时间:2013-11-03 18:40:10

标签: c# .net excel

我有一个包含一些数据的列表数组。目前我可以在控制台中看到输出,现在尝试添加到excel文件。任何人都可以解释我如何做到这一点。这是创建excel表并向其写入内容的代码。但是如何组合这两个代码来查看excel中的输出。我尝试了几种组合,但无法写入excel。我是c#的新手。谢谢!

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();

2 个答案:

答案 0 :(得分:2)

Interop,cell - 有点开销。创建一个空的工作簿并将其另存为二进制资源。无论何时需要创建新文件,只需获取该资源并写入磁盘即可。然后使用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,您只需打开一个连接 - 非常精简,内存有效的方法。

答案 1 :(得分:0)

在您的参考中加入 Excel互操作。这是一些快速而肮脏的代码。请提一下您正在使用哪个框架,因为在v4.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-我没有测试过代码,但你应该可以通过一些小的调整来运行它。