Creating and Writing Excel file in Java

In our earlier post we have learned about creating and writing data to a .txt file in Java.In this tutorial we shall learn about creating and writing data to a excel file.There are two ways in creating an Excel file in Java.We can create it using File class or by using POI library methods.Today, we shall learn about creating the Excel file using File classes.

While creating a .txt file, we have first created an object to the FileOutputStream class and we have used f1.txt as the file path.To create an Excel we need to change the extension to .xls.

FileOutputStream fos = new FileOutputStream("store.xls"); 

In the above described example we are creating an Excel file as store which stores the data of a super market.To save the data in the file we need to use the sequence character \t.we use \t because the width between two columns in Excel sheet is 5 spaces or a single tab.To write the data into the next row of the spread sheet we use the sequence character \n.Now we shall write the program with above information.

import java.io.*;
class fileswritedemoxls
{
	public static void main(String arg[])
		{
			try
			{
	  			String header="Item\tQuantity(kg)\tPrice";
				byte b[] = header.getBytes();
				FileOutputStream fos = new FileOutputStream("store.xls");
				for(int i=0;i<header.length;i++)
				{
					fos.write(b[i]);
				}

				String row1="\nSugar\t2.5\t60";
				byte b1[] = row1.getBytes();
				for(int i=0;i<b1.length;i++)
				{
					fos.write(b1[i]);
				}

				fos.close();
			}
			catch(Exception e)
			{
				System.out.print(e);
			}
		}
}

Description:In the above program we are inserting two rows…..one as heading for the column and other row is the items present in the store.
Output:
filewritedemoxls
filewritedemoxls2

Click here to download the source code

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s