[英]Reading excel file in c# using Microsoft DocumentFormat.OpenXml SDK
[英]Validate Excel file in c# using Documentformat.OpenXML
我在使用DocumentFormat.OpenXML驗證Excel文件時遇到此錯誤(“拋出異常:xunit.assert.dll中為'Xunit.Sdk.EqualException'”)。 我想使用#驗證excel文件,並且正在使用DocumentFormat.OpenXML
using System;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using Xunit;
using P = DocumentFormat.OpenXml.Presentation;
using S = DocumentFormat.OpenXml.Spreadsheet;
using W = DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
namespace ExcelValidation2
{
class Program
{
static void Main(string[] args)
{
var excelFile = "ExcelValidation.xlsx";
var readFile = File.ReadAllBytes(excelFile);
using(MemoryStream ms = new MemoryStream())
{
ms.Write(readFile, 0, readFile.Length);
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(ms, true))
{
//var corePart = doc.CoreFilePropertiesPart;
//var appPart = doc.ExtendedFilePropertiesPart;
//doc.DeletePart(corePart);
//doc.DeletePart(appPart);
//doc.AddCoreFilePropertiesPart();
//doc.AddExtendedFilePropertiesPart();
//doc.AddCustomFilePropertiesPart();
//doc.AddDigitalSignatureOriginPart();
//doc.AddExtendedPart("realType", "contentType/xml", ".xml");
//var tnPart = doc.AddThumbnailPart(ThumbnailPartType.Jpeg);
//doc.DeletePart(tnPart);
//tnPart = doc.AddThumbnailPart("image/jpg");
OpenXmlValidator v = new OpenXmlValidator(DocumentFormat.OpenXml.FileFormatVersions.Office2013);
var errs = v.Validate(doc);
Assert.Equal(1, errs.Count());
}
}
}
}
}
可以檢查此方法來驗證:
private void ValidateExcel()
{
try
{
var validator = new OpenXmlValidator();
int count = 0;
foreach (ValidationErrorInfo error in validator.Validate(SpreadsheetDocument.Open(openFileDialog1.FileName, true)))
{
count++;
lblError.Text += ("Error Count : " + count) + "\r\n";
lblError.Text += ("Description : " + error.Description) + "\r\n";
lblError.Text += ("Path: " + error.Path.XPath) + "\r\n";
lblError.Text += ("Part: " + error.Part.Uri) + "\r\n";
}
Console.ReadKey();
}
catch (Exception ex)
{
lblError.Text += (ex.Message);
}
}
如果未在SpreadsheetDocument或損壞的文檔中讀取excel文件
DocumentFormat.OpenXml.Packaging.OpenXmlPackageException:“指定的程序包無效。 主要部分缺失。”
如果Assert.Equal(1,errs.Count());
System.InvalidOperationException:“ Assert.Equals不應用於斷言,而應使用Assert.AreEqual(...)。”
你可以試試
Assert.Equal(0,errs.Count());
我用
<package id="DocumentFormat.OpenXml" version="2.8.1" targetFramework="net45" /> <package id="NUnit" version="3.10.1" targetFramework="net45" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.