1

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.

3
  • What is the error message that you get on compilation? Commented Oct 7, 2015 at 14:34
  • Possible duplicate of Writing to a particular cell location using Apache POI Excel Commented Oct 7, 2015 at 14:41
  • it gives several error messages ... for example: "; expected" and "illegal character '\' " Commented Oct 7, 2015 at 14:47

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

6 Comments

With the code "XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(new File("C:\\Users\\Username\\Desktop\\java-programs\\results.xlsm")));" at the beginning, it now compiles ... I can even run the program without getting an error message .... Alas, the number "5" is not printed into the excel sheet ... nothing is happening there
Did you write it out with a FileOutputStream?
if I use FileOutputStream, I get the following error message when running the file: "The process cannot access the file because it is being used by another process"
The code I added to the previous code was the following: FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Username\\Desktop\\java-programs\\results.xlsm"); wb.write(fileOut); fileOut.close();
fileIn.close(), then create fileOut.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.