亲宝软件园·资讯

展开

.Net Core使用OpenXML导出导入Excel .Net Core使用OpenXML导出、导入Excel

ZKEASOFT 人气:0
想了解.Net Core使用OpenXML导出、导入Excel的相关内容吗,ZKEASOFT在本文为您仔细讲解.Net Core使用OpenXML导出导入Excel的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:.Net,Core,OpenXML,Excel,下面大家一起来学习吧。

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

Open-XML-SDK

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

依赖 WindowsBase 或 System.IO.Packaging

开源地址: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();
}

导出的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);
    }
   }
  }
 }
}

加载全部内容

相关教程
猜你喜欢
用户评论