我在使用DocumentFormat.OpenXML验证Excel文件时收到此错误("异常抛出:' Xunit.Sdk.EqualException'在xunit.assert.dll"中)。我想使用#验证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());
}
}
}
}
}
答案 0 :(得分:0)
可以检查此方法以进行验证:
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);
}
}
答案 1 :(得分:0)
如果未在SpreadsheetDocument或损坏的文档中读取excel文件
DocumentFormat.OpenXml.Packaging.OpenXmlPackageException:“指定的包无效。缺少主要部分。“
如果Assert.Equal(1,errs.Count());
System.InvalidOperationException:“Assert.Equals不应该用于Assertions,而是使用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" />