c# - 将List中的值导出到excel

标签 c# excel ms-office office-interop excel-interop

嗨,我有一个包含值列表的列表容器。我希望将列表值直接导出到 Excel。有什么办法可以直接实现吗?

最佳答案

好的,如果您想使用 COM,这里有一个分步指南。

  1. 您必须安装 Excel。
  2. 将对您的项目的引用添加到 Excel interop dll。去做这个 在 .NET 选项卡上选择 Microsoft.Office.Interop.Excel。 可能有多个程序集 用这个名字。选择 适合您的 Visual Studio 和 Excel 版本。
  3. 下面是一个代码示例,用于创建新工作簿并用以下内容填充列 您列表中的项目。
<小时/>
using NsExcel = Microsoft.Office.Interop.Excel;

public void ListToExcel(List<string> list)
{
    //start excel
    NsExcel.ApplicationClass excapp = new Microsoft.Office.Interop.Excel.ApplicationClass();

    //if you want to make excel visible           
    excapp.Visible = true;

    //create a blank workbook
    var workbook = excapp.Workbooks.Add(NsExcel.XlWBATemplate.xlWBATWorksheet);

    //or open one - this is no pleasant, but yue're probably interested in the first parameter
    string workbookPath = "C:\test.xls";
    var workbook = excapp.Workbooks.Open(workbookPath,
        0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
        true, false, 0, true, false, false);

    //Not done yet. You have to work on a specific sheet - note the cast
    //You may not have any sheets at all. Then you have to add one with NsExcel.Worksheet.Add()
    var sheet = (NsExcel.Worksheet)workbook.Sheets[1]; //indexing starts from 1

    //do something usefull: you select now an individual cell
    var range = sheet.get_Range("A1", "A1");
    range.Value2 = "test"; //Value2 is not a typo

    //now the list
    string cellName;
    int counter = 1;
    foreach (var item in list)
    {
        cellName = "A" + counter.ToString();
        var range = sheet.get_Range(cellName, cellName);
        range.Value2 = item.ToString();
        ++counter;
    }

    //you've probably got the point by now, so a detailed explanation about workbook.SaveAs and workbook.Close is not necessary
    //important: if you did not make excel visible terminating your application will terminate excel as well - I tested it
    //but if you did it - to be honest - I don't know how to close the main excel window - maybee somewhere around excapp.Windows or excapp.ActiveWindow
}

关于c# - 将List中的值导出到excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2206279/

相关文章:

C# - 一个 Action<> 是否可以有多个方法签名?

c# - 按名称检索文本框

vba - 如何防止 VBA 编辑器删除内部空格?

.net - .NET 应用程序如何与 32 位和 64 位 Office 一起运行?

c# - 如何使用 C#.Net 从 .CAB 文件中提取文件?

c# - 如何在 C# 中使用 LINQ to XML 检查 XDocument 中的属性是否存在

java - 在java中将xls转换为xlsx

c# - 不正确的异步/等待工作,Excel 应用程序级加载项中的 Excel 事件

.net - 以编程方式替换 Word 文档中文本的最快方法

vba - 在用户关闭 Excel 后,在 VBA - excel 中编写宏