2013-12-18 65 views
0
FileInputStream file = new FileInputStream(new File("//Users//"+ usr +"//Desktop//TNA//output//output.xls")); 
HSSFWorkbook workbook = new HSSFWorkbook(file); 
HSSFSheet sheet = workbook.getSheet("Sheet1"); 
Cell name_c = null; 
Cell department_c = null; 
Cell prev_depart_c = null; 
HSSFRow row = sheet.createRow((short) 0); 
HSSFCellStyle style = workbook.createCellStyle(); 
style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index); 
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
department_c = sheet.getRow(2).getCell(1); // throws exception here 
department_c.setCellValue(department); 
prev_depart_c = sheet.getRow(3).getCell(1); 
prev_depart_c.setCellValue(prev_depart); 
emp_no_c = sheet.getRow(4).getCell(1); 
emp_no_c.setCellValue(emp_no); 
file.close(); 
FileOutputStream outFile =new FileOutputStream(new File("//Users//"+ usr +"//Desktop//TNA//output//output10.xls")); 
workbook.write(outFile); 
outFile.close(); 

我想寫現有的excel文件,但它在拋磚引玉的地方拋出了我java.lang.NullPointerException。任何意見或建議,高度讚賞。Java - 無法寫入excel單元

+0

這意味着'sheet.getRow(2)'爲空(asume'workbook.createCellStyle()'不返回空)。 – Ioan

+0

是。那個特定的單元格是空的,我需要在那裏寫入值... –

+0

檢查您的工作表是否有三行 – Deepak

回答

1

在您的代碼中,此行HSSFRow row = sheet.createRow((short) 0);只是在位置0處創建了一個新行。除此之外的任何東西仍然是null,因此當您試圖調用任何方法時會拋出NPE。

爲了能夠在一行中寫入單元格,您需要先在特定位置創建一行。

HSSFRow row = sheet.createRow(2); // create a row at rownum 2 
// use the created row and add/edit cells in it. 
1

如果不已經在工作表上存在的細胞,你需要創建它們:

public class ExcelExample { 

    public static void main(String[] args) throws IOException { 
     FileInputStream file = new FileInputStream(new File("/output.xls")); 
     HSSFWorkbook workbook = new HSSFWorkbook(file); 
     HSSFSheet sheet = workbook.getSheet("Sheet1"); 

     Cell name_c = null; 
     Cell department_c = null; 
     Cell prev_depart_c = null; 


     HSSFRow row = sheet.createRow((short) 0); 
     HSSFCellStyle style = workbook.createCellStyle(); 
     style.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index); 
     style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 

     HSSFRow row2 = sheet.createRow(2); 
     HSSFCell cell = row2.createCell(1); 
     cell.setCellValue("5"); 

     HSSFRow row3 = sheet.createRow(3); 
     HSSFCell cell2 = row2.createCell(1); 
     cell2.setCellValue("5"); 

     file.close(); 
     FileOutputStream outFile =new FileOutputStream(new File("/output10.xls")); 
     workbook.write(outFile); 
     outFile.close(); 
    } 
} 
2

順便說一句,你在你的文件路徑使用冗餘斜線

File("//Users//"+ usr +"//Desktop//TNA//output//output.xls")); 

一斜線就足夠了。斜槓(/)不必像反斜槓那樣在字符串中轉義。