1

我有一个包含一些数据的列表数组。目前我可以在控制台中看到输出,现在尝试添加到 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();
4

2 回答 2

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打开一个连接 - 非常薄,内存效率高的方法。

于 2013-11-04T14:52:01.963 回答
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-我还没有测试过代码,但你应该可以通过一些小调整来运行它。

于 2013-11-03T19:28:48.763 回答