import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class ReadWriteExcel {
public void readExcel(String path) throws BiffException,IOException {
File fileExel = new File(path);
Workbook workbookExcel = Workbook.getWorkbook(fileExel);
Sheet[] workbookSheet = workbookExcel.getSheets();
int baris = workbookSheet[0].getRows();
int kolom = workbookSheet[0].getColumns();
for (int i = 0; i < baris; i++) {
for (int j = 0; j < kolom; j++) {
//format kolom,baris
System.out.print(workbookSheet[0].getCell(j,i).getContents());
System.out.print("\t");
}
System.out.print("\n");
}
}
public void writeExcel(String path) throws WriteException,IOException {
File file = new File(path);
WritableWorkbook workbook = Workbook.createWorkbook(file);
WritableSheet sheet = workbook.createSheet("sheet1", 0);
//format kolom,baris
Label labelNama = new Label(0, 0, "nama");
Label labelDuit = new Label(1, 0, "duit");
Label labelNamaIsi = new Label(0, 1, "choel");
Number numberDuit = new Number(1, 1, 5000000.0);
sheet.addCell(labelNama);
sheet.addCell(labelDuit);
sheet.addCell(labelNamaIsi);
sheet.addCell(numberDuit);
workbook.write();
workbook.close();
}
}
potongan program diatas berisi dua buah method untuk membaca (readExcel) dan menulis (writeExcel) file excel. pada masing2 method terdapat parameter path yang akan menentukan lokasi file yang akan dibaca/ditulis.
berdasarkan pengalaman, proses baca dan tulis hanya dapat dilakukan pada file excel yang ekstensiny *.xls, jika library diatas digunakan untuk baca/tulis file excel yang ekstensiny *.xlsx maka akan menimbulkan exception.
sumber http://hengkysunarno.wordpress.com/2011/02/01/membaca-file-excel-di-java/
kalo ada kesalahan mohon dikoreksi :)
semoga bermanfaat...
No comments:
Post a Comment