实用技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 实用技巧 > .Net Core使用OpenXML导出导入Excel

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

作者:ZKEASOFT

这篇文章主要为大家详细介绍了.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);
    }
   }
  }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文