導(dǎo)出Excel是程序很常用到的功能,.Net Core可以借助Open-XML-SDK來(lái)導(dǎo)出Excel。
Open-XML-SDK
open-xml-sdk是是微軟開(kāi)源的項(xiàng)目。Open XML SDK是用于Open XML文檔(DOCX, XLSX, and PPTX)的開(kāi)源類(lèi)庫(kù)。它可以:
依賴(lài) WindowsBase 或 System.IO.Packaging
開(kāi)源地址:Open-XML-SDK
Nuget:DocumentFormat.OpenXml
Open XML SDK for Office 文檔
示例
首先添加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(); }
導(dǎo)出的Excel如圖:
讀取Excel
讀取Excel的代碼會(huì)相對(duì)簡(jiǎn)單一些:
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); } } } } }
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com