Create a new Java project "JavaExcelRead" and save it somewhere, e.g. "c:/temp/lars.xls".
Create an excel spreadsheet.
Create a package "reader" and the following class "ReadExcel".
I assume that the coding is pretty much self-explaining. I tried to add lots of comments to make it easier to understand.For more complex examples have a look at the excellent documentation of the Java Excel API which is also part of the distribution.
package reader;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WriteException;
public class ReadExcel {
private String inputFile;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public void read() throws IOException, WriteException {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
CellType type = cell.getType();
if (cell.getType() == CellType.LABEL) {
System.out.println("I got a label "
+ cell.getContents());
}
if (cell.getType() == CellType.NUMBER) {
System.out.println("I got a number "
+ cell.getContents());
}
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws WriteException, IOException {
ReadExcel test = new ReadExcel();
test.setInputFile("c:/temp/lars.xls");
test.read();
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment