阅读Excel工作表,处理并输出

时间:2013-10-13 12:12:18

标签: java windows eclipse excel jexcelapi

我正在玩jexcel libary

我尝试编写一个执行以下操作的小程序:

  1. 阅读xls文件
  2. 在工作表中制作一些计算并将其写入另一个地方
  3. public class DataProcessor {

        private String inputFile;
        private String outputFile;
    
    
    
    private Sheet sheet;
        private Workbook w;
    
        public void setInputFile(String inputFile) {
            this.inputFile = inputFile;
        }
    
        public void setOutputFile(String outputFile) {
            this.outputFile = outputFile;
        }
    
        public void read() throws IOException {
            File inputWorkbook = new File(inputFile);
            Workbook w;
            try {
                w = Workbook.getWorkbook(inputWorkbook);
                sheet = w.getSheet(0);
            } catch (BiffException e) {
                e.printStackTrace();
            }
        }
    
        @SuppressWarnings("deprecation")
        public void write() throws IOException, WriteException {
            File file = new File(inputFile);
            WorkbookSettings wbSettings = new WorkbookSettings();
    
            wbSettings.setLocale(new Locale("en", "EN"));
    
            WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
            workbook.createSheet("Lolonator", 0);
            workbook.createSheet("Lolonator123", 1);
            workbook.copy(w);
    
            workbook.write();
            workbook.close();
        }
    
        public static void main(String[] args) throws IOException, WriteException {
            ReadExcel test = new ReadExcel();
            test.setInputFile("C:/Users/Desktop/sheet1.xls");
            test.read();
            System.out.println("####################################################");
            System.out.println("File read!");
    
    //      Write
            System.out.println("####################################################");
            System.out.println("Start to write the file!");
            WriteExcel out = new WriteExcel();
            out.setOutputFile("C:/Users/Desktop/sheet2.xls");
            out.write();
            System.out.println("Please check the result file!");
    
        }
    
    }
    

    然而,这不起作用。我的表格中没有任何输出,即使我的程序无一例外地运行到最后。我非常感谢你的回答!

1 个答案:

答案 0 :(得分:1)

在你的write函数中,你使用“inputFile”作为File构造函数的参数,但是你在创建out对象后没有初始化它。

所以写函数中的以下行

File file = new File(inputFile);

应该是

File file = new File(outputFile);

运行此代码后,您确定没有看到任何错误。它应该抛出空指针异常。

希望这会有所帮助......