gpt4 book ai didi

c# - 使用 Documentformat.OpenXML 在 C# 中验证 Excel 文件

转载 作者:行者123 更新时间:2023-12-05 05:16:11 24 4
gpt4 key购买 nike

我在使用 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);
}
}

关于c# - 使用 Documentformat.OpenXML 在 C# 中验证 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50695580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com