将列表中的数值导出到Excel

27

您好,我有一个列表容器,其中包含值的列表。我希望能够直接将列表值导出到Excel中。是否有任何直接完成此操作的方法?


我希望将它导出到Excel。你们中有谁能给我提供一个示例代码吗? - susanthosh
我在我的帖子中给了您一个链接,其中包含MSDN示例,提供有关如何通过Interop创建和写入数据到Excel文件的示例代码。 - Ian
13个回答

25

如果您想使用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
}

只是需要注意的是:通常在整个电子表格准备好之前,您不希望看到Excel。在这种情况下,您应该将 excapp.Visible = true; 移动到设置表格完成后。 - Tot Zam
对于像我这样遇到ApplicationClass问题的人,这里是解决方案(将Interop.Excel引用的“嵌入互操作类型”设置为“False”):https://dev59.com/YnE95IYBdhLWcg3wDpcG#2483688 - 10101

24
使用 ClosedXML edit 库(无需安装 MS Excel)。
我只是写了一个简单的示例,以展示如何命名文件、工作表并选择单元格。
    var workbook = new XLWorkbook();
    workbook.AddWorksheet("sheetName");
    var ws = workbook.Worksheet("sheetName");

    int row = 1;
    foreach (object item in itemList)
    {
        ws.Cell("A" + row.ToString()).Value = item.ToString();
        row++;
    }

    workbook.SaveAs("yourExcel.xlsx");

如果您愿意,可以创建一个包含所有数据的 System.Data.DataSet 或 System.Data.DataTable,然后只需使用 workbook.AddWorksheet(yourDataset)workbook.AddWorksheet(yourDataTable) 将其添加为工作表;

1
我曾经见过的关于Excel写作最简单和优雅的解决方案,干杯! - Amund Midtskog
1
获取“此网站无法访问”,请给我一个可用的链接,谢谢。 - Aviram Fireberger
旧链接今天无法访问,我认为这个链接可能会有帮助:https://github.com/modulexcite/ClosedXML - Tommaso Cerutti

19

如果它只是一个字符串列表,可以使用CSV的想法。假设l是您的列表:

using System.IO;

using(StreamWriter sw = File.CreateText("list.csv"))
{
  for(int i = 0; i < l.Count; i++)
  {
    sw.WriteLine(l[i]);
  }
}

自定义对象将写入类名。 - Imran Qadir Baksh - Baloch
我只是提到csv不是Excel文件。如果你需要xls文件,请使用Matthew的答案中提到的其他工具 ;) - zolty13

15

1
很不幸,这个项目已经一年没有更新了。看起来它的用户很少,维护也不是很好。 - zolty13
1
我在2022年3月发现了它,并且最近进行了更新。但是,无论它有多老,只要它能正常工作 - 而且对我来说它非常好用。自从EPPlus发布5.0商业版本后,我一直在使用它来处理Blazor WASM浏览器中的数据。 - Ekus
1
我强烈推荐这个!到目前为止我用过的最好的一个! - Morné
有没有人用于大型Excel文件转换效果良好的工具?我的文件有四十万行,但它尝试执行转换时会使用近9GB内存。 - EyeSeeSharp

8
使用ClosedXml是最简单的方法。
Imports ClosedXML.Excel

var dataList = new List<string>() { "a", "b", "c" };
var workbook = new XLWorkbook();     //creates the workbook
var wsDetailedData = workbook.AddWorksheet("data"); //creates the worksheet with sheetname 'data'
wsDetailedData.Cell(1, 1).InsertTable(dataList); //inserts the data to cell A1 including default column name
workbook.SaveAs(@"C:\data.xlsx"); //saves the workbook

更多信息,请查看ClosedXml的维基百科页面。 https://github.com/closedxml/closedxml/wiki


简单而优雅!像魔法一样运行。 - MDe

3

将值列表导出到Excel

  1. 在NuGet中安装以下引用
  2. Install-Package Syncfusion.XlsIO.Net.Core -Version 17.2.0.35
  3. Install-Package ClosedXML -Version 0.94.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClosedXML;
using ClosedXML.Excel;
using Syncfusion.XlsIO;

namespace ExporteExcel
{
    class Program
    {
        public class Auto
        {
            public string Marca { get; set; }

            public string Modelo { get; set; }
            public int Ano { get; set; }

            public string Color { get; set; }
            public int Peronsas { get; set; }
            public int Cilindros { get; set; }
        }
        static void Main(string[] args)
        {
            //Lista Estatica
            List<Auto> Auto = new List<Program.Auto>()
            {
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2019, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2018, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2017, Color= "Azul", Cilindros=6, Peronsas= 4 }
            };
            //Inizializar Librerias
            var workbook = new XLWorkbook();
            workbook.AddWorksheet("sheetName");
            var ws = workbook.Worksheet("sheetName");
            //Recorrer el objecto
            int row = 1;
            foreach (var c in Auto)
            {
                //Escribrie en Excel en cada celda
                ws.Cell("A" + row.ToString()).Value = c.Marca;
                ws.Cell("B" + row.ToString()).Value = c.Modelo;
                ws.Cell("C" + row.ToString()).Value = c.Ano;
                ws.Cell("D" + row.ToString()).Value = c.Color;
                ws.Cell("E" + row.ToString()).Value = c.Cilindros;
                ws.Cell("F" + row.ToString()).Value = c.Peronsas;
                row++;

            }
            //Guardar Excel 
            //Ruta = Nombre_Proyecto\bin\Debug
            workbook.SaveAs("Coches.xlsx");
        }
    }
}

1
这个很好用,但是如何添加列标题? - user7998549

2
您可以将它们输出到一个.csv文件,然后在Excel中打开该文件。这样直接明了吗?

1

在我看来,最直接的方法是简单地组合一个 CSV 文件。如果你想要进行格式化并实际写入 *.xlsx 文件,则有更复杂的解决方案(以及 API)可以为您完成。


0
List<"classname"> getreport = cs.getcompletionreport(); 

var getreported = getreport.Select(c => new { demographic = c.rName);   

cs.getcompletionreport() 引用的类文件是应用程序的业务层
希望这可以帮到你。


因为它看起来像这样http://i.imgur.com/5ngtPac.png,我希望您同意这种方式更易于阅读和将代码与答案的其余部分视觉上分离。 - Misa Lazovic

0
将列表传递到“Write”方法中,该方法将把列表转换为缓冲区并返回缓冲区,从而下载文件。
byte[] buffer = Write(ListData, true, "AttendenceSummary"); return File(buffer, "application/excel", reportTitle + ".xlsx");

      public static byte[] Write<T>(IEnumerable<T> list, bool xlsxExtension, string sheetName = "ExportData")
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            XSSFWorkbook hssfworkbook = new XSSFWorkbook();
            int Rowspersheet = 15000;
            int TotalRows = list.Count();
            int TotalSheets = TotalRows / Rowspersheet;

            for (int i = 0; i <= TotalSheets; i++)
            {
                ISheet sheet1 = hssfworkbook.CreateSheet(sheetName + "_" + i);
                IRow row = sheet1.CreateRow(0);
                int index = 0;
                foreach (PropertyInfo property in typeof(T).GetProperties())
                {
                    ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
                    IFont cellFont = hssfworkbook.CreateFont();

                    cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                    cellStyle.SetFont(cellFont);

                    ICell cell = row.CreateCell(index++);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(property.Name);
                }

                int rowIndex = 1;
                // int rowIndex2 = 1;

                foreach (T obj in list.Skip(Rowspersheet * i).Take(Rowspersheet))
                {

                    row = sheet1.CreateRow(rowIndex++);
                    index = 0;

                    foreach (PropertyInfo property in typeof(T).GetProperties())
                    {
                        ICell cell = row.CreateCell(index++);
                        cell.SetCellValue(Convert.ToString(property.GetValue(obj)));
                    }

                }
            }

            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            return file.ToArray();

        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接