
how to create an excel file using java

Hi Friend,
Try the following code:
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
public class CreateExcelFile{
public static void main(String[]args){
try{
String filename="c:/hello.xls" ;
HSSFWorkbook hwb=new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.createCell((short) 0).setCellValue("SNo");
rowhead.createCell((short) 1).setCellValue("First Name");
rowhead.createCell((short) 2).setCellValue("Last Name");
rowhead.createCell((short) 3).setCellValue("Username");
rowhead.createCell((short) 4).setCellValue("E-mail");
rowhead.createCell((short) 5).setCellValue("Country");
HSSFRow row= sheet.createRow((short)1);
row.createCell((short) 0).setCellValue("1");
row.createCell((short) 1).setCellValue("Rose");
row.createCell((short) 2).setCellValue("India");
row.createCell((short) 3).setCellValue("roseindia");
row.createCell((short) 4).setCellValue("hello@roseindia.net");
row.createCell((short) 5).setCellValue("India");
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch ( Exception ex ) {
System.out.println(ex);
}
}
}
For the above code, you need apache poi library.
Thanks

this API is Deprecated . Please use int instead of short.

how can I create xlsx document? Thank you for help. Brane

package newpack;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
//import org.apache.poi.hssf.usermodel.HSSFCell;
public class CreateExcel{ public static void main(String[]args){ try{ String filename="c:/hello.xls" ; HSSFWorkbook hwb=new HSSFWorkbook(); HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead= sheet.createRow((short)0); rowhead.createCell((short) 0).setCellValue("Name"); rowhead.createCell((short) 1).setCellValue("Salary");
FileOutputStream fileOut = new FileOutputStream(filename); hwb.write(fileOut); fileOut.close(); System.out.println("Your excel file has been generated!");
} catch ( Exception ex ) { System.out.println(ex);
} } } I used jre jdk 1.4 version and poi 2.5 . This code works .
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.