将List中的值导出为ex​​cel

时间:2010-02-05 09:45:26

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

您好我有一个包含值列表的列表容器。我希望将列表值直接导出到Excel。有没有办法直接这样做?

13 个答案:

答案 0 :(得分:18)

好的,如果你想使用COM,这是一个循序渐进的指南。

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

  4. 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
    }
    

答案 1 :(得分:13)

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

using System.IO;

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

答案 2 :(得分:10)

使用ClosedXML库(无需安装MS Excel

我只是写一个简单的例子来向您展示如何命名文件,工作表和选择单元格:

File cacheDir = getApplicationContext().getFilesDir();

如果您愿意,可以使用所有数据创建System.Data.DataSet或System.Data.DataTable,然后将其添加为包含 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"); workbook.AddWorksheet(yourDataset)的工作集;

答案 3 :(得分:4)

快速方式-ArrayToExcel (github)

byte[] excel = myList.ToExcel();
File.WriteAllBytes("result.xlsx", excel);

答案 4 :(得分:1)

您可以将它们输出到.csv file并在Excel中打开文件。那是否足够直接?

答案 5 :(得分:1)

最简单的方法(在我看来)就是简单地整理一个CSV文件。如果你想进入格式化并实际写入* .xlsx文件,那么有更复杂的解决方案(和APIs)可以帮助你。

答案 6 :(得分:1)

将值列表导出到Excel

  1. 在nuget中安装下一个参考
  2. 安装包Syncfusion.XlsIO.Net.Core-版本17.2.0.35
  3. 安装包ClosedXML-版本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");
        }
    }
}

答案 7 :(得分:0)

根据您想要执行此操作的环境,可以使用Excel Interop。然而,处理COM并确保清理资源非常混乱,否则Excel实例会在您的计算机上闲置。

如果您想了解更多信息,请查看此MSDN Example

根据您的格式,您可以自己制作CSV或SpreadsheetML,这不是太难。其他替代方法是使用第三方库来执行此操作。显然他们要花钱。

答案 8 :(得分:0)

一种简单的方法是打开包含要导出的测试数据的Excel创建工作表,然后说excel另存为xml打开xml,看看excel期望的xml格式,并通过替换测试数据来生成它导出数据

SpreadsheetML Markup Spec

@lan这是一个simle execel文件的xml,其中一个列值与office 2003一致,此格式适用于office 2003及以上版本

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>Dancho</Author>
  <LastAuthor>Dancho</LastAuthor>
  <Created>2010-02-05T10:15:54Z</Created>
  <Company>cc</Company>
  <Version>11.9999</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>13800</WindowHeight>
  <WindowWidth>24795</WindowWidth>
  <WindowTopX>480</WindowTopX>
  <WindowTopY>105</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="6" x:FullColumns="1"
   x:FullRows="1">
   <Row>
    <Cell><Data ss:Type="String">Value1</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value2</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value3</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value4</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value5</Data></Cell>
   </Row>
   <Row>
    <Cell><Data ss:Type="String">Value6</Data></Cell>
   </Row>
  </Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <Selected/>
   <Panes>
    <Pane>
     <Number>3</Number>
     <ActiveRow>5</ActiveRow>
    </Pane>
   </Panes>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet2">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
 <Worksheet ss:Name="Sheet3">
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>

答案 9 :(得分:0)

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

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

其中cs.getcompletionreport()引用类文件是App的业务层 我希望这会有所帮助。

答案 10 :(得分:0)

使用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的wiki。 https://github.com/closedxml/closedxml/wiki

答案 11 :(得分:0)

我知道,我参加这个聚会很晚,但是我认为这可能对其他人有帮助。

已经发布的答案是针对csv的,其他答案是Interop dll的,您需要在服务器上安装excel,每种方法都有其优点和缺点。 这是一个可以为您提供

的选项
  1. 完美的excel输出[不是csv]
  2. 凭借完美的excel和您的数据类型匹配
  3. 没有excel安装
  4. 通过列表并获得Excel输出:)

您可以通过使用NPOI DLL来实现此目的,该{.3和.net核心都可以使用

步骤:

  1. 导入NPOI DLL
  2. 添加下面提供的第1节和第2节代码
  3. 很好走

第1

此代码执行以下任务:

  1. 创建新的Excel对象-_workbook = new XSSFWorkbook();
  2. 创建新的Excel工作表对象-_sheet =_workbook.CreateSheet(_sheetName);
  3. 调用WriteData()-稍后说明最后,创建和
  4. 返回MemoryStream对象

================================================ =============================

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace GenericExcelExport.ExcelExport
{
    public interface IAbstractDataExport
    {
        HttpResponseMessage Export(List exportData, string fileName, string sheetName);
    }

    public abstract class AbstractDataExport : IAbstractDataExport
    {
        protected string _sheetName;
        protected string _fileName;
        protected List _headers;
        protected List _type;
        protected IWorkbook _workbook;
        protected ISheet _sheet;
        private const string DefaultSheetName = "Sheet1";

        public HttpResponseMessage Export
              (List exportData, string fileName, string sheetName = DefaultSheetName)
        {
            _fileName = fileName;
            _sheetName = sheetName;

            _workbook = new XSSFWorkbook(); //Creating New Excel object
            _sheet = _workbook.CreateSheet(_sheetName); //Creating New Excel Sheet object

            var headerStyle = _workbook.CreateCellStyle(); //Formatting
            var headerFont = _workbook.CreateFont();
            headerFont.IsBold = true;
            headerStyle.SetFont(headerFont);

            WriteData(exportData); //your list object to NPOI excel conversion happens here

            //Header
            var header = _sheet.CreateRow(0);
            for (var i = 0; i < _headers.Count; i++)
            {
                var cell = header.CreateCell(i);
                cell.SetCellValue(_headers[i]);
                cell.CellStyle = headerStyle;
            }

            for (var i = 0; i < _headers.Count; i++)
            {
                _sheet.AutoSizeColumn(i);
            }

            using (var memoryStream = new MemoryStream()) //creating memoryStream
            {
                _workbook.Write(memoryStream);
                var response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(memoryStream.ToArray())
                };

                response.Content.Headers.ContentType = new MediaTypeHeaderValue
                       ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.Content.Headers.ContentDisposition = 
                       new ContentDispositionHeaderValue("attachment")
                {
                    FileName = $"{_fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
                };

                return response;
            }
        }

        //Generic Definition to handle all types of List
        public abstract void WriteData(List exportData);
    }
}

================================================ =============================

第2节

在第2节中,我们将执行以下步骤:

  1. 将列表转换为DataTable Reflection以读取属性名称,您的
  2. 列标题将来自此处
  3. 遍历DataTable以创建excel行

================================================ =============================

using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text.RegularExpressions;

namespace GenericExcelExport.ExcelExport
{
    public class AbstractDataExportBridge : AbstractDataExport
    {
        public AbstractDataExportBridge()
        {
            _headers = new List<string>();
            _type = new List<string>();
        }

        public override void WriteData<T>(List<T> exportData)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));

            DataTable table = new DataTable();

            foreach (PropertyDescriptor prop in properties)
            {
                var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
                _type.Add(type.Name);
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? 
                                  prop.PropertyType);
                string name = Regex.Replace(prop.Name, "([A-Z])", " $1").Trim(); //space separated 
                                                                           //name by caps for header
                _headers.Add(name);
            }

            foreach (T item in exportData)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }

            IRow sheetRow = null;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                sheetRow = _sheet.CreateRow(i + 1);
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    ICell Row1 = sheetRow.CreateCell(j);

                    string type = _type[j].ToLower();
                    var currentCellValue = table.Rows[i][j];

                    if (currentCellValue != null && 
                        !string.IsNullOrEmpty(Convert.ToString(currentCellValue)))
                    {
                        if (type == "string")
                        {
                            Row1.SetCellValue(Convert.ToString(currentCellValue));
                        }
                        else if (type == "int32")
                        {
                            Row1.SetCellValue(Convert.ToInt32(currentCellValue));
                        }
                        else if (type == "double")
                        {
                            Row1.SetCellValue(Convert.ToDouble(currentCellValue));
                        }
                    }
                    else
                    {
                        Row1.SetCellValue(string.Empty);
                    }
                }
            }
        }
    }
}

================================================ =============================

现在您只需要打电话 通过传递列表来实现WriteData()函数,它将为您提供出色的表现。

我已经在WEB API和WEB API核心中对其进行了测试,就像是一种魅力。

答案 12 :(得分: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();

        }