java – 使用Apache POI更新excel文件
发布时间:2020-12-15 02:49:43 所属栏目:Java 来源:网络整理
导读:我正在尝试使用Apache POI更新现有的Excel文件.每次运行我的代码时,都会收到错误,如下所示.我也尝试了FileInputStreamNewFile的事情. Exception in thread "main" java.lang.NullPointerException at com.gma.test.WriteExcelTest.writeXLSXFile(WriteExcelT
我正在尝试使用Apache POI更新现有的Excel文件.每次运行我的代码时,都会收到错误,如下所示.我也尝试了FileInputStreamNewFile的事情.
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:AnujDataData.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:AnujDataData.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); } } 解决方法
如果你更换
//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"); 它会工作! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |