public void main2(String[] args) throws Exception { TextDocument textdoc=(TextDocument)TextDocument.loadDocument("D:/HelloWorld.odt"); TextNavigation search1; search1=new TextNavigation("What",textdoc); while (search1.hasNext()) { TextSelection item1 = (TextSelection) search1.nextSelection(); System.out.println(item1); } TextNavigation search2 = null; search2 = new TextNavigation("What", textdoc); while (search2.hasNext()) { TextSelection item= (TextSelection) search2.nextSelection(); item.replaceWith("replacedest"); } textdoc.save("D:/HelloWorld2.odt"); }
ODS範例
public static void main(String[] args) throws Exception { System.out.println("START"); SpreadsheetDocument ods = SpreadsheetDocument.newSpreadsheetDocument(); Table table = Table.newTable(ods, 4000, 20, 0, 0); table.setTableName("foo"); //create style OdfOfficeAutomaticStyles astyles = ods.getContentDom().getOrCreateAutomaticStyles(); StyleStyleElement ele = astyles.newStyleStyleElement(OdfStyleFamily.TableCell.getName(), "myss"); StyleTableCellPropertiesElement styleTableCellPropertiesElement = ele.newStyleTableCellPropertiesElement(); styleTableCellPropertiesElement.setFoBackgroundColorAttribute("#A5A5A5"); styleTableCellPropertiesElement.setFoBorderAttribute("1.0pt solid #000000"); ele.newStyleParagraphPropertiesElement().setFoTextAlignAttribute(HorizontalAlignmentType.CENTER.toString()); StyleTextPropertiesElement styleTextPropertiesElement = ele.newStyleTextPropertiesElement(null); styleTextPropertiesElement.setStyleFontNameAttribute("Arial"); styleTextPropertiesElement.setFoFontSizeAttribute("7.0pt"); styleTextPropertiesElement.setFoColorAttribute(Color.BLACK.toString()); styleTextPropertiesElement.setFoFontWeightAttribute("bold"); List rows = table.getRowList(); for (Row r : rows) { for (int a = 0; a < 10; a++) { Cell cell = r.getCellByIndex(a); cell.setStringValue("Foo " + a); cell.setCellStyleName("myss"); } } ods.save("D:/foo2.ods"); System.out.println("END"); }
讀檔
SpreadsheetDocument workbook = null; Cell cell = null; File tmpFile = new File("tmp.ods") try { workbook = SpreadsheetDocument.loadDocument(tmpFile); Table sheet = workbook.getSheetByIndex(0); int rows = sheet.getRowCount(); for (int row = 1;row < rows;row++) { String rowStr1 = sheet.getCellByPosition(0, row).getStringValue(); } workbook.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (workbook != null) { workbook.close(); } }