2015-08-28 2 views
4

Я пытаюсь обновить существующий файл Excel с помощью Apache POI. Каждый раз, когда я запускаю свой код, я получаю сообщение об ошибке, как показано ниже. Я также попробовал FileInputStreamNewFile.Обновление файла excel с использованием Apache POI

Exception in thread "main" java.lang.NullPointerException 
    at com.gma.test.WriteExcelTest.writeXLSXFile(WriteExcelTest.java:26) 
    at com.gma.test.WriteExcelTest.main(WriteExcelTest.java:44) 

Пожалуйста, найдите код ниже. Ценю вашу помощь.

package com.gma.test; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 

import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.xssf.usermodel.XSSFCell; 
import org.apache.poi.xssf.usermodel.XSSFRow; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class WriteExcelTest { 

    public static void writeXLSXFile(int row, int col) throws IOException { 
     try { 
      FileInputStream file = new FileInputStream("C:\\Anuj\\Data\\Data.xlsx"); 

      XSSFWorkbook workbook = new XSSFWorkbook(file); 
      XSSFSheet sheet = workbook.getSheetAt(0); 
      Cell cell = null; 

      //Update the value of cell 
      cell = sheet.getRow(row).getCell(col); 
      cell.setCellValue("Pass"); 

      file.close(); 

      FileOutputStream outFile =new FileOutputStream(new File("C:\\Anuj\\Data\\Data.xlsx")); 
      workbook.write(outFile); 
      outFile.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 
     writeXLSXFile(3, 3); 
    } 

} 
+0

проверить, если sheet.getRow (строка) не равно нулю, то ячейка не нуль перед установкой значения –

+0

Если вы запрашиваете подряд | ячейка, которая не определена, вы получаете нуль! –

ответ

6

Если заменить

//Update the value of cell 
cell = sheet.getRow(row).getCell(col); 
cell.setCellValue("Pass"); 

С

//Retrieve the row and check for null 
HSSFRow sheetrow = sheet.getRow(row); 
if(sheetrow == null){ 
    sheetrow = sheet.createRow(row); 
} 
//Update the value of cell 
cell = sheetrow.getCell(col); 
if(cell == null){ 
    cell = sheetrow.createCell(col); 
} 
cell.setCellValue("Pass"); 

Она будет работать!

+1

Что делать, если sheet.getRow (row) return Null? –

+0

Сделайте аналогичную проверку в строке –

+0

Да, строки и ячейки основаны на 0, поэтому в примере, если у него нет значения на D4, он получит исключение NullPointerException. –

3

Спасибо Jelle Heuzel за то, что вы нашли хороший пример.
Я просто хотел добавить полученный рабочий код, чтобы другие могли быстрее включить его в свой код.

Мне также пришлось использовать XSSFRow вместо HSSFRow, но кроме этого он отлично работает для меня.

package stackoverflow.appachePOI; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 

import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.xssf.usermodel.XSSFRow; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class WriteExcelTest { 

    public static void writeXLSXFile(int row, int col) throws IOException { 
     try { 
      FileInputStream file = new FileInputStream("C:\\Users\\Sam\\files\\Masterproef lca\\lca-analysebeheer\\Test-Files\\exceltemplates\\template.xlsx"); 

      XSSFWorkbook workbook = new XSSFWorkbook(file); 
      XSSFSheet sheet = workbook.getSheetAt(0); 
      Cell cell = null; 

      //Retrieve the row and check for null 
      XSSFRow sheetrow = sheet.getRow(row); 
      if(sheetrow == null){ 
       sheetrow = sheet.createRow(row); 
      } 
      //Update the value of cell 
      cell = sheetrow.getCell(col); 
      if(cell == null){ 
       cell = sheetrow.createCell(col); 
      } 
      cell.setCellValue("Pass"); 

      file.close(); 

      FileOutputStream outFile =new FileOutputStream(new File("C:\\Users\\Sam\\files\\Masterproef lca\\lca-analysebeheer\\Test-Files\\exceltemplates\\Output.xlsx")); 
      workbook.write(outFile); 
      outFile.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 
     writeXLSXFile(3, 3); 
    } 

} 
+0

Исключает нулевой указатель здесь XSSFheet sheet = workbook.getSheetAt (0); Кто-нибудь здесь ? –

+0

Первое, что-то пошло не так в вашем потоке, и ваша книга не может быть создана. – turoni

1

я пытался с этим и работы XLSX и XSSF

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 

import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.xssf.usermodel.XSSFRow; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class TestStackOver { 

    public static void writeXLSXFile(int row, int col) throws IOException { 
     try { 
      FileInputStream file = new FileInputStream(Constante.ruta); 
      XSSFWorkbook workbook = new XSSFWorkbook(file); 
      XSSFSheet sheet = workbook.getSheetAt(0); 
      Cell cell = null; 
      //Retrieve the row and check for null 
      XSSFRow sheetrow = sheet.getRow(row); 
      if(sheetrow == null){ 
       sheetrow = sheet.createRow(row); 
      } 
      //Update the value of cell 
      cell = sheetrow.getCell(col); 
      if(cell == null){ 
       cell = sheetrow.createCell(col); 
      } 
      cell.setCellValue("Pass"); 

      file.close(); 


      FileOutputStream outFile =new FileOutputStream(new File(Constante.ruta_salida)); 
      workbook.write(outFile); 
      outFile.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 
     System.out.println("inicio"); 
     writeXLSXFile(1, 14); 
     System.out.println("terminado"); 
    } 

} 
Смежные вопросы