保存Excel文档Apache POI

时间:2014-04-30 10:49:01

标签: java excel apache-poi

我需要从excel文档创建通知,我使用Java和Apache POI。这是我的代码:

    //Get path with JFileChooser
    public static String LeeRuta(){
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        chooser.showDialog(chooser, "Seleccionar");
        File f =chooser.getSelectedFile();
        File camino = f.getAbsoluteFile();
        String ruta = camino.getAbsolutePath();
        return ruta;
    }

  //main
  public static void main(String args[]) {
    String ruta=LeeRuta();

    /* Don't know if neccesary, but it didn't works with or without it
    InputStream inp;
    try {
        inp = new FileInputStream(ruta);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(PruebaExcel.class.getName()).log(Level.SEVERE, null, ex);
    }
    */

    Workbook exceldoc = null;

    // Opening file
      try {
         exceldoc = WorkbookFactory.create(new File(ruta));
        //wb = WorkbookFactory.create(new File(ruta));
    } catch (InvalidFormatException | IOException e) {
        e.printStackTrace();
    }


    //Selecting the sheet
    String nombredoc = exceldoc.getSheetName(0);
    Sheet hoja = exceldoc.getSheet(nombredoc);


        //Selecting the cell
        Cell celda = hoja.getRow(1).getCell(1);
//        System.out.println(celda);
        System.out.println(hoja.getRow(2).getCell(3));

        //Variables
        int anyo = 2014;
        String ota = "OTa 158";

        //Setting Cells value
        hoja.getRow(2).getCell(4).setCellValue(anyo);
        hoja.getRow(2).getCell(5).setCellValue(ota);

       //If I print here cell values, I see that values has been set.

        //Saving
        try {
            //hoja.getRow(3).getCell(4).setCellValue(fecha);
            FileOutputStream out = new FileOutputStream("C:\\Documents and Settings\\INGENIERIA2\\Mis documentos\\Informe.xls");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PruebaExcel.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            exceldoc.write(out);
        } catch (IOException ex) {
            Logger.getLogger(PruebaExcel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

问题是Informe.xls文件为空(文件大小= 0 KB),Excel表示其已损坏或已损坏。我想我在输出流和写入方面表现不佳,但不知道如何修复它。

2 个答案:

答案 0 :(得分:7)

无法编译的源代码:您在 try-catch 范围内定义变量 out ,然后在另一个 try-catch 中使用它。

试试这段代码:

try {
    FileOutputStream out = new FileOutputStream("C:\\Documents and Settings\\INGENIERIA2\\Mis documentos\\Informe.xls");
    exceldoc.write(out);
    out.close();
} catch (FileNotFoundException ex) {
    Logger.getLogger(PruebaExcel.class.getName()).log(Level.SEVERE, null, ex);
}

答案 1 :(得分:0)

这个怎么样,

try (FileOutputStream out = new FileOutputStream("C:\\file\\path\\here\\Informe.xls")) {
    exceldoc.write(out);
} catch (FileNotFoundException ex) {
    Logger.getLogger(PruebaExcel.class.getName()).log(Level.SEVERE, null, ex);
}