1 Jakarta POI Jakarta POI (http://jakarta.apache.org/poi/index.html) jest zbiorem narzędzi umożliwiającym prace z dokumentami zapisanymi w formatach wspieranych przez Microsoft. W skład POI wchodzą następujące komponenty: POIFS obsługa dokumentów OLE 2, HSSF dokumenty w formacie Excel'a, HWPF proste dokumenty w formacie Word 97, HPSF własności dokumentów OLE 2 (tytuł, autor, data ostatniej modyfikacji,...).
HSSF w skrócie odczyt i zapis arkusza: POIFSFileSystem fs = new POIFSFileSystem( new FileInputStream("input.xls")); HSSFWorkbook wb = new HSSFWorkbook(fs); FileOutputStream fileout = new FileOutputStream("output.xls"); wb.write(fileout); fileout.close(); nowy, pusty dokument: HSSFWorkbook wb = new HSSFWorkbook(); nowy arkusz: HSSFSheet sheet1 = wb.createsheet("pierwszy arkusz"); HSSFSheet sheet2 = wb.createsheet("drugi arkusz"); 2
dodawanie komórek do formularza: daty HSSF w skrócie HSSFRow row = sheet.createrow((short)0); HSSFCell cell = row.createcell((short)0); cell.setcellvalue(1); row.createcell((short)1).setcellvalue("jakis tekst"); row.createcell((short)2).setcellvalue(true); HSSFCell cell = row.createcell((short)3); cell.setcellvalue(new Date()); HSSFCellStyle cellstyle = wb.createcellstyle(); cellstyle.setdataformat( HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); cell = row.createcell((short)4); cell.setcellvalue(new Date()); cell.setcellstyle(cellstyle); 3
4 HSSF w skrócie justowanie: HSSFCell cell = row.createcell((short)5); cell.setcellvalue("justowanie"); HSSFCellStyle cellstyle = wb.createcellstyle(); cellstyle.setalignment(hssfcellstyle.align_center); cell.setcellstyle(cellstyle); Więcej informacji: http://jakarta.apache.org/poi/hssf/quick-guide.html.
5 Przykład Jako przykład zastosowania pakietu Jakarta POI przygotujemy klasę rozszerzającą JTable o metodę public void exporttable(file file), która zapisuje dane znajdujące się w tabeli do pliku xls. JXMLTable TableRow 1 A Literka a 2 B Literka b 3 C Literka c 4 D Literka d
6 TableRow.java public interface TableRow { public Object getattribute(int i); public void setattribute(int i, Object obj); public boolean iseditable(int i); Interfejs określa metody obiektu, który może być umieszczony w naszej tabeli.
7 TestObject.java import java.util.date; public class TestObject implements TableRow { private int id; private String name; private String description; private Date date; public TestObject(int i, String s1, String s2, Date d) { this.id = i; this.name = s1; this.description = s2; this.date = d; public boolean iseditable(int i) { if (this.id > 0) return true; return false;
8 TestObject.java public Object getattribute(int i) { switch (i) { case 0: return new Integer(this.id); case 1: return this.name; case 2: return this.description; case 3: return this.date; default: return null;
TestObject.java public void setattribute(int i, Object obj) { switch (i) { case 0: if (obj instanceof Integer) { this.id = ((Integer) obj).intvalue(); break; case 1: if (obj instanceof String) { this.name = (String) obj; break; case 2: if (obj instanceof String) { this.description = (String) obj; break; case 3: if (obj instanceof Date) { this.date = (Date) obj; break; default: return; 9
10 Model tabeli Dane, oraz inne informacje potrzebne do wyświetlenia tabeli JTable są zwykle pamiętane w instancji klasy JTableModel. Pozwala to na rozdzielenie danych, sposobu prezentacji i widoku. Model TableModel Widok JTable
XSLTableModel.java iimport javax.swing.table.abstracttablemodel; public class XLSTableModel extends AbstractTableModel { private static final int columncount = 4; private static final int[] columnwidths = { 100, 150, 100, 50 ; private static final String[] columnnames = { "pierwsza", "druga", "trzecia", "czwarta" ; private static final String[] columntips = { "pierwsza kolumna", "druga kolumna", "trzecia kolumna", "czwarta kolumna" ; private TableRow[] rows; public XLSTableModel(TableRow[] tra) { super(); this.rows = tra; public void update(tablerow[] tra) { this.rows = tra; public TableRow getobjectat(int rowindex) { if (rowindex >= 0 && rowindex > this.rows.length) return this.rows[rowindex]; return null; 11
12 XSLTableModel.java public int getrowcount() { return this.rows.length; public int getcolumncount() { return columncount; public String getcolumnname(int i) { return columnnames[i]; public Class getcolumnclass(int i) { if (this.rows.length > 0) { return this.rows[0].getattribute(i).getclass(); return String.class; public int getcolumnwidth(int i) { return columnwidths[i];
XSLTableModel.java public String getcolumntip(int i) { return columntips[i]; public boolean iscelleditable(int row, int column) { TableRow tr = this.rows[row]; if (tr!= null) return tr.iseditable(column); return false; public Object getvalueat(int row, int column) { TableRow tr = this.rows[row]; if (tr!= null) return tr.getattribute(column); return null; public void setvalueat(object avalue, int row, int column) { Object obj = getvalueat(row, column); if (avalue == null avalue.equals(obj)) return; TableRow tr = this.rows[row]; tr.setattribute(column, avalue); 13
14 JXLSTable.java... import org.apache.poi.hssf.usermodel.hssfcell; import org.apache.poi.hssf.usermodel.hssfrow; import org.apache.poi.hssf.usermodel.hssfsheet; import org.apache.poi.hssf.usermodel.hssfworkbook; public class JXLSTable extends JTable { protected JTableHeader createdefaulttableheader() { return new JTableHeader(this.columnModel) { public String gettooltiptext(mouseevent e) { Point p = e.getpoint(); int index = this.columnmodel.getcolumnindexatx(p.x); if (index < 0) return null; int realindex = this.columnmodel.getcolumn(index).getmodelindex(); return ((XLSTableModel) JXLSTable.this.getModel()).getColumnTip(realIndex); ;
JXLSTable.java public JXLSTable(TableRow[] ta) { super(); this.setmodel(new XLSTableModel(ta)); public void exporttable(file file) { int irow, icolumn, i; Object obj; TableCellRenderer r; Component c; String stmp; HSSFRow row; HSSFCell cell; HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createsheet(); TableModel tm = this.getmodel(); row = sheet.createrow(sheet.getphysicalnumberofrows()); for (icolumn=0, i=0; icolumn<tm.getcolumncount(); icolumn++) { stmp = tm.getcolumnname(icolumn); if (stmp == null) stmp = ""; cell = row.createcell((short) i); cell.setencoding(hssfcell.encoding_utf_16); cell.setcellvalue(stmp); i++; 15
16 JXLSTable.java for (irow = 0; irow < tm.getrowcount(); irow++) { row = sheet.createrow(sheet.getphysicalnumberofrows()); for (icolumn=0, i=0; icolumn<tm.getcolumncount(); icolumn++){ cell = row.createcell((short) i); obj = tm.getvalueat(irow, icolumn); stmp = ""; if (obj!= null) { r = this.getcellrenderer(irow, icolumn); c = this.preparerenderer(r, irow, icolumn); if (c!= null) { if (c instanceof JLabel) stmp = ((JLabel) c).gettext(); else stmp = obj.tostring(); // if c // if obj cell.setencoding(hssfcell.encoding_utf_16); cell.setcellvalue(stmp); i++; // for // for
17 JXLSTable.java try { FileOutputStream fos = new FileOutputStream(file); workbook.write(fos); fos.close(); catch (IOException e) { e.printstacktrace();
Example.java Klasa Example służy do przetestowania przygotowanego pakietu narzędzi: import... public class Example implements ActionListener { private JXLSTable table; private JTextField filename; public static void main(string[] args) { TestObject[] toa = new TestObject[4]; toa[0] = new TestObject(1, "a", "literka a", new Date()); toa[1] = new TestObject(2, "b", "literka b", new Date()); toa[2] = new TestObject(3, "c", "literka c", new Date()); toa[3] = new TestObject(4, "d", "literka d", new Date()); JXLSTable table = new JXLSTable(toa); JScrollPane sp = new JScrollPane(table); JTextField tf = new JTextField("output.xls"); Example ex = new Example(); ex.filename = tf; ex.table = table; 18
Example.java JButton b = new JButton("Export"); b.setactioncommand("export"); b.addactionlistener(ex); JPanel p = new JPanel(new BorderLayout()); p.add(tf, BorderLayout.NORTH); p.add(sp, BorderLayout.CENTER); p.add(b, BorderLayout.SOUTH); JFrame f = new JFrame("XLSExample"); f.getcontentpane().add(p); f.pack(); f.setlocationrelativeto(null); f.setdefaultcloseoperation(jframe.exit_on_close); f.setvisible(true); public void actionperformed(actionevent ae) { if (ae.getactioncommand().equals("export")) { this.table.exporttable(new File(this.filename.getText())); JOptionPane.showMessageDialog(null, "plik zosta\u0142 zapisany", "Informacja", JOptionPane.INFORMATION_MESSAGE); 19
20 Uruchomienie programu do ścieżki klas należy dodać bibliotekę poi-2.0-final-20040126.jar kompilacja i uruchomienie za pomocą komend javac i java.
21 Podsumowanie Dzięki różnorodnym bibliotekom programy napisane w Javie mogą obsługiwać wiele formatów dokumentów. Projekt Jakarta POI jest jednym z przykładów takiej powszechnie wykorzystywanej, biblioteki.