.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)的开源类库。它可以:
- 生成Word,Excel,PPT时有非常好的性能
- 从XML数据源中填充内容到Word文档中
- 可将单个Word,Excel,PPT分成多个文件或者将多个合并到一个文件中
- DOCX => HTML/CSS 和 HTML/CSS => DOCX 提供友好便捷的方式
- 提取Excel中的数据
- 用正则表达式查找或者替换DOCX / PPTX中的内容
- 更新 DOCX / 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);
}
}
}
}
}
以上是 .Net Core使用OpenXML导出、导入Excel 的全部内容, 来源链接: utcz.com/z/313287.html