tags:

views:

694

answers:

7

i just want to read and write a excel file from java.No complex calcutionns needed I just want to creat a excel sheet with 3 col and n rows. Like printing one string in each cell.

Can anyone giv me simple code snippet ofr this? Do i need to use any external lib or do java have build in support for it?

i want to do following

for(i=0 ;i <rows ;i++)
     //read [i,col1] ,[i,col2] and [i,col3]

for(i=o;i<rows;i++
  //write [i,col1],[i,col2] [i,col3]
+1  A: 

Apache POI can do this for you. Specifically the HSSF module. The quick guide is most useful. Here's how to do what you want - specifically create a sheet and write it out.

    Workbook wb = new HSSFWorkbook();
    //Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet("new sheet");

    // Create a row and put some cells in it. Rows are 0 based.
    Row row = sheet.createRow((short)0);
    // Create a cell and put a value in it.
    Cell cell = row.createCell(0);
    cell.setCellValue(1);

    // Or do it on one line.
    row.createCell(1).setCellValue(1.2);
    row.createCell(2).setCellValue(
         createHelper.createRichTextString("This is a string"));
    row.createCell(3).setCellValue(true);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();
Brian Agnew
+9  A: 

Try the Apache POI HSSF. Here's an example on how to read an excel file:

try {
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
    HSSFWorkbook wb = new HSSFWorkbook(fs);
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row;
    HSSFCell cell;

    int rows; // No of rows
    rows = sheet.getPhysicalNumberOfRows();

    int cols = 0; // No of columns
    int tmp = 0;

    // This trick ensures that we get the data properly even if it doesn't start from first few rows
    for(int i = 0; i < 10 || i < rows; i++) {
        row = sheet.getRow(i);
        if(row != null) {
            tmp = sheet.getRow(i).getPhysicalNumberOfCells();
            if(tmp > cols) cols = tmp;
        }
    }

    for(int r = 0; r < rows; r++) {
        row = sheet.getRow(r);
        if(row != null) {
            for(int c = 0; c < cols; c++) {
                cell = row.getCell((short)c);
                if(cell != null) {
                    // Your code here
                }
            }
        }
    }
} catch(Exception ioe) {
    ioe.printStackTrace();
}

On the documentation page you also have examples of how to write to excel files.

rogeriopvl
+3  A: 

A simple CSV file should suffice

gnibbler
Beware that you will have to escape commas within the strings you write to the CSV.
Brian Agnew
Indeed CSV is enough. If your fields have no commas, it is probably easiest just to print the fields and commas. Otherwise, you may want to use http://commons.apache.org/sandbox/csv/
Yuval F
I'm not sure a CSV *is* enough, since the question specifically says 'read' and 'write' an Excel file. He might be able to get away with CSV, but that's not what he's asking.
Brian Agnew
Some international versions of Excel use semicolons instead of commas as separators. This also increases complexity
Roalt
A: 

If you need to do anything more with office documents in Java, go for POI as mentioned.

For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class CsvWriter {
 public static void main(String args[]) throws IOException {

  String fileName = "test.xls";

  PrintWriter out = new PrintWriter(new FileWriter(fileName));
  out.println("a,b,c,d");
  out.println("e,f,g,h");
  out.println("i,j,k,l");
  out.close();

  BufferedReader in = new BufferedReader(new FileReader(fileName));
  String line = null;
  while ((line = in.readLine()) != null) {

   Scanner scanner = new Scanner(line);
   String sep = "";
   while (scanner.hasNext()) {
    System.out.println(sep + scanner.next());
    sep = ",";
   }
  }
  in.close();
 }
}
Adriaan Koster
+2  A: 

.csv or POI will certainly do it, but you should be aware of Andy Khan's JExcel. I think it's by far the best Java library for working with Excel there is.

duffymo
+3  A: 

You can also consider JExcelApi. I find it better designed than POI. There's a tutorial here.

javashlook
A: 

You can try SmartXLS,it is a commercial excel spreadsheet component which support most excel features like charts,images,comments,pivottables...,it also has a runtime calculation engine support 300+ excel formulas.

liya