我遇到一种情况,我试图处理表中的行负载,并使用jxl将结果(成功或异常)输出到excel电子表格。问题是我看不到如何将已启动的Excel工作簿传递给catch块,以便可以将异常打印到它。下面是一些简化的代码,概述了我的程序的结构(忽略任何基本错误,我只是出于演示目的将其键入):
public static void main(String[] args) {
try{
WritableWorkbook exceptionWB=Workbook.createWorkbook(new File("filename.xls");
WritableSheet excepSheet=exceptionWB.createSheet("Exceptions",0);
int exceptionRow=1;
for(int i=0; i<numberOfRecords;i++){
processRow(argument1, argument2, excepSheet, exceptionRow);
}
catch (Exception e){
Label exception1=new Label(0, exceptionRow, e.getMessage());
exceptionWB.write();
}
}
public void processRow(String arg1, String arg2, WritableSheet sheet, int row){
try{
// A load of operations here
} catch(Exception e) {
Label exception1=new Label(0, exceptionRow, e.getMessage());
exceptionWB.write();
}
}
我知道catch块无法访问工作表,因为它不在范围内,但是如果我将Workbook初始化移出try块,则会返回一个错误,因为它周围没有异常处理。
是否可以通过此方法将WorkBook / Sheet传递到各个捕获块,还是我应该完全考虑一个完全不同的解决方案?
谢谢
像这样定义它:
public static void main(String[] args) {
WritableWorkbook exceptionWB = null;
try{
exceptionWB = Workbook.createWorkbook(new File("filename.xls");
WritableSheet excepSheet=exceptionWB.createSheet("Exceptions",0);
int exceptionRow=1;
for(int i=0; i<numberOfRecords;i++) {
processRow(argument1, argument2, excepSheet, exceptionRow);
}
catch (Exception e) {
//You should now have access to the exceptionWB
Label exception1=new Label(0, exceptionRow, e.getMessage());
exceptionWB.write();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句