导出Excel是程序很常用到的功能,.Net Core可以借助Open-XML-SDK来导出Excel。

Open-XML-SDK

open-xml-sdk是是微软开源的项目。Open XML SDK是用于Open XML文档(DOCX, XLSX, and PPTX)的开源类库。它可以:

  • 生成Word,Excel,PPT时有非常好的性能
  • 从XML数据源中填充内容到Word文档中
  • 可将单个Word,Excel,PPT分成多个文件或者将多个合并到一个文件中
  • DOCX => HTML/CSS 和 HTML/CSS => DOCX 提供友好便捷的方式
  • 提取Excel中的数据
  • 用正则表达式查找或者替换DOCX / PPTX中的内容
  • 更新 DOCX / PPTX 中缓存的数据或者嵌入的表格.
  • 文档内容的修改, 例如从文件中删除跟踪的修订或删除不可接受的内容.

依赖 WindowsBase 或 System.IO.Packaging

Platform System.IO.Packing Source Tested by
.NET 3.5 WindowsBase N/A
.NET 4.0 WindowsBase .NET 4.5.2
.NET 4.6 NuGet .NET 4.6
.NET Standard NuGet .NET Core 1.0

开源地址:https://github.com/OfficeDev/Open-XML-SDK

Nuget:https://www.nuget.org/packages/DocumentFormat.OpenXml

Open XML SDK for Office 文档

http://msdn.microsoft.com/en-us/library/office/bb448854.aspx

示例

首先添加Nuget包引用

直接上代码:

static void Main(string[] args)
{
    var spreadsheetDocument = SpreadsheetDocument.Create("F:\\OpenXml.xlsx", SpreadsheetDocumentType.Workbook);
    var workbookpart = spreadsheetDocument.AddWorkbookPart();
    workbookpart.Workbook = new Workbook();
    WorksheetPart worksheetPart = workbookpart.AddNewPart();
    worksheetPart.Worksheet = new Worksheet(new SheetData());
    Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
    Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
    sheets.Append(sheet);
    var sheetData = worksheetPart.Worksheet.GetFirstChild();
    for (int i = 0; i < 10; i++)
    {
        Row row = new Row();
        for (int j = 0; j < 10; j++)
        {
            Cell dataCell = new Cell();
            dataCell.CellValue = new CellValue($"{i + 1}行{j + 1}列");
            dataCell.DataType = new EnumValue(CellValues.String);
            row.AppendChild(dataCell);
        }
        sheetData.Append(row);
    }


    workbookpart.Workbook.Save();
    spreadsheetDocument.Close();
}

导出的Excel如图:

读取Excel

读取Excel的代码会相对简单一些:

static void Main(string[] args)
{
    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(@"F:\OpenXml.xlsx", false))
    {
        WorkbookPart wbPart = doc.WorkbookPart;
        Sheet mysheet = (Sheet)doc.WorkbookPart.Workbook.Sheets.ChildElements.FirstOrDefault();
        Worksheet worksheet = ((WorksheetPart)wbPart.GetPartById(mysheet.Id)).Worksheet;
        SheetData sheetData = (SheetData)worksheet.ChildElements.FirstOrDefault();

        foreach (var row in sheetData.ChildElements)
        {
            foreach (var cell in (row as Row).ChildElements)
            {
                var cellValue = (cell as Cell).CellValue;
                if (cellValue != null)
                {
                    Console.WriteLine(cellValue.Text);
                }
            }
        }
    }
}

测试的代码在 .Net Core 2.0 完美运行