导出Excel是程序很常用到的功能,.Net Core可以借助Open-XML-SDK来导出Excel。
open-xml-sdk是是微软开源的项目。Open XML SDK是用于Open XML文档(DOCX, XLSX, and PPTX)的开源类库。它可以:
开源地址:https://github.com/OfficeDev/Open-XML-SDK
Nuget:https://www.nuget.org/packages/DocumentFormat.OpenXml
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如图:
原文地址:http://www.zkea.net/codesnippet/detail/post-69