我需要将一个 .xlsx 文件导入到我的 WPF 应用程序中并查看它。我将文档转换为 .xps 格式,然后进行加载操作。之后我调用
GetFixedDocumentSequence()
方法,但是出现了以下异常:
XamlParseException:
{"UnicodeString property does not contain enough characters to correspond to the contents of Indices property."}.
这是我的代码:
private void LoadData()
{
string xpsPath = ViewDocumentViewer("D:\\test.xlsx");
DisplayXPSFile(xpsPath);
}
private string ViewDocumentViewer(string path)
{
try
{
string xpsPath;
var excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.DisplayAlerts = false;
excelApp.Visible = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(path);
xpsPath = ExportXPS(excelWorkbook, path);
excelWorkbook.Close(false, null, null);
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
excelApp = null;
return xpsPath;
}
catch
{
}
return string.Empty;
}
string ExportXPS(Microsoft.Office.Interop.Excel.Workbook excelWorkbook, string path)
{
string xpsFileName;
xpsFileName = (new DirectoryInfo(path)).FullName;
xpsFileName = xpsFileName.Replace(new FileInfo(path).Extension, "") + ".xps";
excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypeXPS,
Filename: xpsFileName,
OpenAfterPublish: false);
return xpsFileName;
}
void DisplayXPSFile(string xpsFileName)
{
XpsDocument xpsPackage = new XpsDocument(xpsFileName, FileAccess.Read, CompressionOption.NotCompressed);
FixedDocumentSequence fixedDocumentSequence = xpsPackage.GetFixedDocumentSequence();
DocView.Document = fixedDocumentSequence;
}