加载Excel文件时获取警告
Contents
[
Hide
]
可能的使用场景
有时用户尝试加载略有损坏但可加载的工作簿。在这种情况下,Aspose.Cells在加载工作簿时会抛出警告。您可以通过实现 IWarningCallback 接口并设置 LoadOptions.WarningCallback 属性来捕获这些警告。
加载 Excel 文件时获取警告
以下示例代码解释了如何在加载excel文件时获取警告。该代码加载示例excel文件,在加载时会生成 DuplicateDefinedName 警告。然后通过 IWarningCallback.Warning() 方法捕获该警告并在控制台上打印警告消息。代码然后将工作簿保存为输出excel文件。如果您在Microsoft Excel中打开示例excel文件,它也会显示您此警告,如下图所示。还请检查下面给出的代码的控制台输出以获取更多理解。
示例代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Implement IWarningCallback interface to catch warnings while loading workbook | |
public class WarningCallback implements IWarningCallback | |
{ | |
public void warning(WarningInfo warningInfo) | |
{ | |
if(warningInfo.getWarningType() == WarningType.DUPLICATE_DEFINED_NAME) | |
{ | |
System.out.println("Duplicate Defined Name Warning: " + warningInfo.getDescription()); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(GetWarningLoadingAnExcel.class) + "loading_saving/"; | |
//Create load options and set the WarningCallback property | |
//to catch warnings while loading workbook | |
LoadOptions options = new LoadOptions(); | |
options.setWarningCallback(new WarningCallback()); | |
//Load the source excel file | |
Workbook book = new Workbook(dataDir + "sampleDuplicateDefinedName.xlsx", options); | |
//Save the workbook | |
book.save(dataDir + "outputDuplicateDefinedName.xlsx"); |
控制台输出
执行上述代码时,以下是控制台输出的代码,提供了 示例excel文件。
Duplicate Defined Name Warning: Name:PRINT_AREA;ReferTo:Introduction!$D$16:$D$17
Duplicate Defined Name Warning: Name:PRINT_AREA;ReferTo:Panel!$B$228
Duplicate Defined Name Warning: Name:PRINT_AREA;ReferTo:'Queries '!$D$14:$D$16