Java Program To write Data In Excel File

In this instructional exercise, you will perceive how to compose on an exceed expectations sheet by utilizing Java. Or in easy words, you will learn, how to write data or insert data into excel file in Java. For this, you need a library called POI which will peruse and write in exceed expectations sheet.

POI is a noticeable API that empowers programming specialists to make, change, and show MS Office records using Java programs.

Java Program To Write Data In Excel File

We need certain container documents to get to the POI library. We essentially need four container records that can work the exceed expectations sheet utilizing java. At that point, import the required bundles from container documents. The required container document bundles are:

  1. import org.apache.poi.ss.usermodel.Cell;
  2. import org.apache.poi.ss.usermodel.Row;
  3. import org.apache.poi.ss.usermodel.Sheet;
  4. import org.apache.poi.ss.usermodel.Workbook;

Then you have to create particular objects.
The following objects you need is:

public static Workbook wb;
public static Sheet s;
public static FileInputStream fi;
public static FileOutputStream fo;

once you mentioned all the files we need to open the file in the main function. Suppose we have one excel file named data.xlsx
First, create one excel file by-

fi=new FileInputStream("data.xlsx");

Once you are done with accessing file name create the workbook by  command:

wb=WorkbookFactory.create(fi);

Then write below command to access a sheet:

s=wb.getSheet("sheet");

Now, you need to clarify how many rows you need to enter in excel file. You can enter as many of the data you need to write in an excel file by using for loop.
you can create a row by using CreateRow() function and to set the value in that row use SetCellValue() function.

The below code will help you to write a data in an excel file:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

import org.apache.poi.ss.usermodel.*;

public class ExcelDemo
{
    public static Workbook wb;
    public static Sheet s;
    public static FileInputStream fi;
    public static FileOutputStream fo;
    public static Row r;
    public static Cell c;
    
    public static void main(String[] args) throws Exception
    {
        fi=new FileInputStream("data.xlsx");
        wb=WorkbookFactory.create(fi);
        s=wb.getSheet("sheet");
        //create one row
        r=s.createRow(1);
        c=row.createCell(0);
        c.setCellValue("Raj");
        System.out.println(c.getStringCellValue());
        fo=new FileOutputStream("data.xlsx");
        wb.write(fo);
        fo.flush();
        fo.close();

        System.out.println("Data entered in a Data excel file");
    }
}





I hope, this tutorial gives you a clear idea on how to insert data into excel file in Java.

Also learn:

Leave a Reply

Your email address will not be published. Required fields are marked *