2013-12-18 36 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")); 

一斜线就足够了。斜杠(/)不必像反斜杠那样在字符串中转义。