I would like to write to a cell on sheet 2, but the operation errors and I get this message :
Exception in thread "main" java.lang.NullPointerException
at Testnextsheet.Testnextsheet.main(Testnextsheet.java:43)
public static void main(String[] args) throws IOException{
try{
FileInputStream files = new FileInputStream(new File("d:\\Materi\\Selenium\\Projects\\Excel\\Book1.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(files);
//----Sheet 1-------------------------------------//
XSSFSheet sheet1 = workbook.getSheet("Sheet1");
//---sheet 2--------------------------------------//
XSSFSheet sheet2 = workbook.getSheet("Sheet2");
//-----------write text to sheet 2------------------------//
sheet2.getRow(3).getCell(2).setCellValue("Test");
FileOutputStream fout= new FileOutputStream(new File("d:\\Materi\\Selenium\\Projects\\Excel\\Book1.xlsx"));
workbook.write(fout);
workbook.close();
files.close();
}
catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
The sheet2 object,which is a TreeMap is empty in the beginning.You need to create a row, then cell and then set the value, something like below-
sheet2.createRow(2).createCell(1).setCellValue("Test");
In your case,sheet2.getRow(3) will throw NullPointerException.
The suggested way would be to iterate the XSSFWorkbook object to access the XSSFSheet and then create as many row and cell as you want and keep on setting the values.
Related
I'm trying to create a simple Excel file in XLSX format.
I can create the old XLS files but when I try to create the other format, the file is always corrupt.
I'm using Apache POI 4.1.1.
This is my simple code:
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
try {
wb.write(fo);
fo.flush();
fo.close();
wb.close();
}catch (Exception e) {
e.printStackTrace();
}
And this is the error message: Error
Use
org.apache.poi.ss.usermodel.WorkbookFactory
//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true); //true creates XSSF formatted file
will return you an instance of
org.apache.poi.ss.usermodel.Workbook
Then you can write to the file using
Workbook.write(OutputStream)
Solution:
try (Workbook wb = WorkbookFactory.create(true)) {
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
wb.write(fos);
}
}
I have to select the option one after another from dropdown say (AAA,BBB... GGG) and after selection whatever the data populate have to be written on excel. Here method clickOnPerfomanceDetails() contains the code to write it down onto Excel. My following code is writing successfully onto excel with different sheets but manually i comment other options. In all 7 times i am executing the script to get data into 7 different worksheet.
public void clickOnPerformanceDetails() throws Exception {
File file = new File("C:\\Users\\dp\\Desktop\\Performance.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
XSSFSheet sheet = wb.createSheet("AAA");
//XSSFSheet sheet = wb.createSheet("BBB");
//XSSFSheet sheet = wb.createSheet("CCC");
// XSSFSheet sheet = wb.createSheet("DDD");
//CODE
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\Performance.xlsx");
wb.write(fos);
fos.close();
}
#Test()
public void providerTest1() throws Exception {
performance_PlusTWO.hoverTest();
performance_PlusTWO.clickOnHieararchyDropDown();
performance_PlusTWO.selectOptionNais();
//AAA
performance_PlusTWO.selectAAAOption();
performancePlus_TWO.clickOnPerformanceDetails();
//BBB
//performance_PlusTWO.selectBBBOption();
//performanceP_TWO.clickOnPerformanceDetails();
//CCC
performance_PlusTWO.selectAAAOption();
performance_TWO.clickOnPerformanceDets();
}
Creating 'AAA' worksheet and running Test for performance_PlusTWO.selectAAAOption();
performancePlus_TWO.clickOnPerformanceDetails(); Then manually i comment 'AAA' option, uncomment 'BBB' option and again execute the script. How do on a single click i execute the data for all the options.
Any help will be appreciated.
Try the below approach.
public void WriteToExcelSheet(String SheetName) throws Exception {
File file = new File("C:\\Users\\dp\\Desktop\\Performance.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
XSSFSheet sheet = wb.createSheet(SheetName);
//CODE
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\Performance.xlsx");
wb.write(fos);
fos.close();
}
#Test()
public void providerTest1() throws Exception {
Select dropdown = new Select(driver.findElement(By.id("id")));
//Get all options
List<WebElement> dropdown_items = dropdown.getOptions();
//print the number of dropdown items
System.out.println(dropdown_items.size());
// Loop through all items one by one
for (int itemIndex = 0; j < dd.size(); j++) {
String option = dropdown_items.get(itemIndex).getText();
//print the sheet name
System.out.println(option);
// write the logic to select the option <=== don't forget to implement this
// logic to call function with sheet name
performance_TWO.WriteToExcelSheet(option);
}
}
I have a Java method writeToExcel(String sheetName, Map), which creates a new sheet with name 'sheetName' in a new excel file and write the map data into it . When I call the method with different sheetName arguments more than once, existing sheet gets replaced by the last called one. I want to create new sheets in the same excel file each time whenever the method is called with different sheetName argument, without losing existing sheets. Here is my code.
public static void writeToExcel(String fileName,Map<Integer,String[]> excelData){
String filePath="/Data/excel.xlsx";
XSSFWorkbook workbook=new XSSFWorkbook();
XSSFSheet sheet=workbook.createSheet(fileName);
Set<Integer> keySet=excelData.keySet();
int passedCount=0;
int failedCount=0;
int rowNo=0;
int cellNo=0;
Row row;
Cell cell;
try{
File file=new File(filePath);
FileOutputStream output=new FileOutputStream(file);
for(Integer key:keySet){
row=sheet.createRow(rowNo++);
String[] dataToWrite=excelData.get(key);
cellNo=0;
for(String str:dataToWrite){
cell=row.createCell(cellNo++);
cell.setCellValue(str);
}
}
workbook.write(output);
output.close();
workbook.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
Seems like you're always creating a new workbook in the second line of the method. So it is not the sheet that is replaced but the entire workbook. Better use
XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath));
That should do the trick.
XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath)); => XSSFWorkbook workbook=new XSSFWorkbook(filePath); as no suit constructor for XSSFWorkbook workbook=new XSSFWorkbook(new File(filePath))
I simply want to put the result of a Java program into an Excel cell. Let's assume the result is 5, then my code in main() would look like this:
XSSFWorkbook wb = C:\Users\Username\Desktop\java-programs\results.xlsm;
XSSFSheet ExcelSheet = wb.getSheet("numbers");
XSSFRow row = ExcelSheet.getRow(0);
XSSFCell cell = row.getCell(0);
cell.setCellValue(5);
However, this code doesn't compile.
I read some examples on this topic but the code given simply refers to the Excel sheet as (e.g.) "sheet" and then goes on with sheet.getRow(some number). The examples don't explain how I tell Java which workbook to write to.
Your first line is incorrect.. try this:
String fileName = "C:/Users/Username/Desktop/java-programs/results.xlsm";
FileInputStream fileIn = new FileInputStream(fileName);
Workbook wb = WorkbookFactory.create(fileIn);
// update the workbook
wb.getSheet("numbers").getRow(0).getCell(0).setCellValue(5);
fileIn.close();
FileOutputStream fileOut = new FileOutputStream(fileName);
wb.write(fileOut);
fileOut.close();
I have a method that reads an excel sheet using Apache POI library. To make that method generic, I need to to write some code in a catch block. Here's the method:
private List<String[]> readFile(String filePath) throws IOException{
List<String[]> sheetValues = new ArrayList<String[]>();
//Two types of fileInputStreams for both the types of workbook i am about to use
//
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
FileInputStream fileInputStream2 = new FileInputStream(new File(filePath));
LineItemFileReader fileReader = new LineItemFileReaderImpl();
//If the file is in xls format i should use HSSFWorkbook
//If the file is in xlsx format i should use XSSFWorkbook
try {
//If the file is in xlsx format then the below line will throw the
//Exception and catch block code will be executed
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
} catch (OfficeXmlFileException exception){
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream2);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
sheetValues = fileReader.ParseSheet(workbook.getSheetAt(1),evaluator);
} finally{
fileInputStream.close();
fileInputStream2.close();
}
return sheetValues;
}
So what's happening here is that I dont know what type of file I am being supplied. I am deciding that on the basis of the try/catch block given above. So is there any generic way of deciding which workbook to use? Since the above code has flow control logic written in a catch block, it's a bad practice.
Use WorkbookFactory.create(...) for opening the Workbook. It will create the appropriate subclass internally:
Workbook workbook = WorkbookFactory.create(new File(filePath));
// ...
workbook.close();