Rising Sun

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            148 隨筆 :: 0 文章 :: 22 評論 :: 0 Trackbacks

          #

          Features

          New Workbook

              //創建新的Excel 工作簿
          ??? HSSFWorkbook wb = new HSSFWorkbook();
          //new 一個FileOutputStream FileOutputStream fileOut = new FileOutputStream("workbook.xls");
          ????//寫入流 wb.write(fileOut); fileOut.close();

          New Sheet

              HSSFWorkbook wb = new HSSFWorkbook();
            // 如要新建一名為"效益指標"的工作表,其語句為:
           // HSSFSheet sheet = workbook.createSheet("效益指標");
          HSSFSheet sheet1 = wb.createSheet("new sheet"); HSSFSheet sheet2 = wb.createSheet("second sheet"); FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();

          Creating Cells

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
          
              // Create a row and put some cells in it. Rows are 0 based.

          ?????//創建一行并放一些元素值 ,0是起始行 HSSFRow row = sheet.createRow((short)0); // Create a cell and put a value in it.
          創建一個單元格 HSSFCell cell = row.createCell((short)0); cell.setCellValue(1); // Or do it on one line.
          創建單元格也可以一行代碼 row.createCell((short)1).setCellValue(1.2); row.createCell((short)2).setCellValue("This is a string"); row.createCell((short)3).setCellValue(true); // Write the output to a file
          FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();

          Creating Date Cells

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
          
              // Create a row and put some cells in it. Rows are 0 based.
              HSSFRow row = sheet.createRow((short)0);
          
              // Create a cell and put a date value in it.  The first cell is not styled
              // as a date.
              HSSFCell cell = row.createCell((short)0);
              cell.setCellValue(new Date());
          
              // we style the second cell as a date (and time).  It is important to
              // create a new cell style from the workbook otherwise you can end up
              // modifying the built in style and effecting not only this cell but other cells.
              HSSFCellStyle cellStyle = wb.createCellStyle();
              cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
              cell = row.createCell((short)1);
              cell.setCellValue(new Date());
              cell.setCellStyle(cellStyle);
          
              // Write the output to a file
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Working with different types of cells不同類型的單元格一起工作

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
              HSSFRow row = sheet.createRow((short)2);
              row.createCell((short) 0).setCellValue(1.1);
              row.createCell((short) 1).setCellValue(new Date());
              row.createCell((short) 2).setCellValue("a string");
              row.createCell((short) 3).setCellValue(true);
              row.createCell((short) 4).setCellType(HSSFCell.CELL_TYPE_ERROR);
          
              // Write the output to a file
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Demonstrates various alignment options示范不同的對齊選項

              public static void main(String[] args)
                      throws IOException
              {
                  HSSFWorkbook wb = new HSSFWorkbook();
                  HSSFSheet sheet = wb.createSheet("new sheet");
                  HSSFRow row = sheet.createRow((short) 2);
                  createCell(wb, row, (short) 0, HSSFCellStyle.ALIGN_CENTER);
                  createCell(wb, row, (short) 1, HSSFCellStyle.ALIGN_CENTER_SELECTION);
                  createCell(wb, row, (short) 2, HSSFCellStyle.ALIGN_FILL);
                  createCell(wb, row, (short) 3, HSSFCellStyle.ALIGN_GENERAL);
                  createCell(wb, row, (short) 4, HSSFCellStyle.ALIGN_JUSTIFY);
                  createCell(wb, row, (short) 5, HSSFCellStyle.ALIGN_LEFT);
                  createCell(wb, row, (short) 6, HSSFCellStyle.ALIGN_RIGHT);
          
                  // Write the output to a file
                  FileOutputStream fileOut = new FileOutputStream("workbook.xls");
                  wb.write(fileOut);
                  fileOut.close();
          
              }
          
              /**
               * Creates a cell and aligns it a certain way.
               *
               * @param wb        the workbook
               * @param row       the row to create the cell in
               * @param column    the column number to create the cell in
               * @param align     the alignment for the cell.
               */
              private static void createCell(HSSFWorkbook wb, HSSFRow row, short column, short align)
              {
                  HSSFCell cell = row.createCell(column);
                  cell.setCellValue("Align It");
                  HSSFCellStyle cellStyle = wb.createCellStyle();
                  cellStyle.setAlignment(align);
                  cell.setCellStyle(cellStyle);
              }
                              

          Working with borders設置邊框

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
          
              // Create a row and put some cells in it. Rows are 0 based.
              HSSFRow row = sheet.createRow((short) 1);
          
              // Create a cell and put a value in it.
              HSSFCell cell = row.createCell((short) 1);
              cell.setCellValue(4);
          
              // Style the cell with borders all around.
              HSSFCellStyle style = wb.createCellStyle();
              style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
              style.setBottomBorderColor(HSSFColor.BLACK.index);
              style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
              style.setLeftBorderColor(HSSFColor.GREEN.index);
              style.setBorderRight(HSSFCellStyle.BORDER_THIN);
              style.setRightBorderColor(HSSFColor.BLUE.index);
              style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);
              style.setTopBorderColor(HSSFColor.BLACK.index);
              cell.setCellStyle(style);
          
              // Write the output to a file
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Fills and colors填充 和 顏色

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
          
              // Create a row and put some cells in it. Rows are 0 based.
              HSSFRow row = sheet.createRow((short) 1);
          
              // Aqua background
              HSSFCellStyle style = wb.createCellStyle();
              style.setFillBackgroundColor(HSSFColor.AQUA.index);
              style.setFillPattern(HSSFCellStyle.BIG_SPOTS);
              HSSFCell cell = row.createCell((short) 1);
              cell.setCellValue("X");
              cell.setCellStyle(style);
          
              // Orange "foreground", foreground being the fill foreground not the font color.
              style = wb.createCellStyle();
              style.setFillForegroundColor(HSSFColor.ORANGE.index);
              style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
              cell = row.createCell((short) 2);
              cell.setCellValue("X");
              cell.setCellStyle(style);
          
              // Write the output to a file
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Merging cells 合并單元格

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
          
              HSSFRow row = sheet.createRow((short) 1);
              HSSFCell cell = row.createCell((short) 1);
              cell.setCellValue("This is a test of merging");
          
              sheet.addMergedRegion(new Region(1,(short)1,1,(short)2));
          
              // Write the output to a file
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Working with fonts 字體

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
          
              // Create a row and put some cells in it. Rows are 0 based.
              HSSFRow row = sheet.createRow((short) 1);
          
              // Create a new font and alter it.
              HSSFFont font = wb.createFont();
              font.setFontHeightInPoints((short)24);
              font.setFontName("Courier New");
              font.setItalic(true);
              font.setStrikeout(true);
          
              // Fonts are set into a style so create a new one to use.
              HSSFCellStyle style = wb.createCellStyle();
              style.setFont(font);
          
              // Create a cell and put a value in it.
              HSSFCell cell = row.createCell((short) 1);
              cell.setCellValue("This is a test of fonts");
              cell.setCellStyle(style);
          
              // Write the output to a file
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Custom colors 自定義顏色

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet();
              HSSFRow row = sheet.createRow((short) 0);
              HSSFCell cell = row.createCell((short) 0);
              cell.setCellValue("Default Palette");
          
              //apply some colors from the standard palette,
              // as in the previous examples.
              //we'll use red text on a lime background
          
              HSSFCellStyle style = wb.createCellStyle();
              style.setFillForegroundColor(HSSFColor.LIME.index);
              style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
          
              HSSFFont font = wb.createFont();
              font.setColor(HSSFColor.RED.index);
              style.setFont(font);
          
              cell.setCellStyle(style);
          
              //save with the default palette
              FileOutputStream out = new FileOutputStream("default_palette.xls");
              wb.write(out);
              out.close();
          
              //now, let's replace RED and LIME in the palette
              // with a more attractive combination
              // (lovingly borrowed from freebsd.org)
          
              cell.setCellValue("Modified Palette");
          
              //creating a custom palette for the workbook
              HSSFPalette palette = wb.getCustomPalette();
          
              //replacing the standard red with freebsd.org red
              palette.setColorAtIndex(HSSFColor.RED.index,
                      (byte) 153,  //RGB red (0-255)
                      (byte) 0,    //RGB green
                      (byte) 0     //RGB blue
              );
              //replacing lime with freebsd.org gold
              palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);
          
              //save with the modified palette
              // note that wherever we have previously used RED or LIME, the
              // new colors magically appear
              out = new FileOutputStream("modified_palette.xls");
              wb.write(out);
              out.close();
                              

          Reading and Rewriting Workbooks? 讀和 重寫工作簿

              POIFSFileSystem fs      =
                      new POIFSFileSystem(new FileInputStream("workbook.xls"));
              HSSFWorkbook wb = new HSSFWorkbook(fs);
              HSSFSheet sheet = wb.getSheetAt(0);
              HSSFRow row = sheet.getRow(2);
              HSSFCell cell = row.getCell((short)3);
              if (cell == null)
                  cell = row.createCell((short)3);
              cell.setCellType(HSSFCell.CELL_TYPE_STRING);
              cell.setCellValue("a test");
          
              // Write the output to a file
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Using newlines in cells? 換行

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet s = wb.createSheet();
              HSSFRow r = null;
              HSSFCell c = null;
              HSSFCellStyle cs = wb.createCellStyle();
              HSSFFont f = wb.createFont();
              HSSFFont f2 = wb.createFont();
          
              cs = wb.createCellStyle();
          
              cs.setFont( f2 );
              //Word Wrap MUST be turned on
              cs.setWrapText( true );
          
              r = s.createRow( (short) 2 );
              r.setHeight( (short) 0x349 );
              c = r.createCell( (short) 2 );
              c.setCellType( HSSFCell.CELL_TYPE_STRING );
              c.setCellValue( "Use \n with word wrap on to create a new line" );
              c.setCellStyle( cs );
              s.setColumnWidth( (short) 2, (short) ( ( 50 * 8 ) / ( (double) 1 / 20 ) ) );
          
              FileOutputStream fileOut = new FileOutputStream( "workbook.xls" );
              wb.write( fileOut );
              fileOut.close();

          Data Formats? 數據格式

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("format sheet");
              HSSFCellStyle style;
              HSSFDataFormat format = wb.createDataFormat();
              HSSFRow row;
              HSSFCell cell;
              short rowNum = 0;
              short colNum = 0;
          
              row = sheet.createRow(rowNum++);
              cell = row.createCell(colNum);
              cell.setCellValue(11111.25);
              style = wb.createCellStyle();
              style.setDataFormat(format.getFormat("0.0"));
              cell.setCellStyle(style);
          
              row = sheet.createRow(rowNum++);
              cell = row.createCell(colNum);
              cell.setCellValue(11111.25);
              style = wb.createCellStyle();
              style.setDataFormat(format.getFormat("#,##0.0000"));
              cell.setCellStyle(style);
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Fit Sheet to One Page?? 一頁中顯視合適的工作表

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("format sheet");
              HSSFPrintSetup ps = sheet.getPrintSetup();
              
              sheet.setAutobreaks(true);
              
              ps.setFitHeight((short)1);
              ps.setFitWidth((short)1);
          
          
              // Create various cells and rows for spreadsheet.
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Set Print Area 設置打印區

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("Sheet1");
              wb.setPrintArea(0, "$A$1:$C$2");
              //sets the print area for the first sheet
              //Alternatively:
              //wb.setPrintArea(0, 0, 1, 0, 0) is equivalent to using the name reference (See the JavaDocs for more details)  
          
              // Create various cells and rows for spreadsheet.
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
              
              
                              

          Set Page Numbers on Footer 設置頁數 在頁用中

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("format sheet");
              HSSFFooter footer = sheet.getFooter()
              
              footer.setRight( "Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages() );
              
          
          
              // Create various cells and rows for spreadsheet.
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Using the Convenience Functions? 行用方便的方法

          The convenience functions live in contrib and provide utility features such as setting borders around merged regions and changing style attributes without explicitly creating new styles.

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet1 = wb.createSheet( "new sheet" );
          
              // Create a merged region
              HSSFRow row = sheet1.createRow( (short) 1 );
              HSSFRow row2 = sheet1.createRow( (short) 2 );
              HSSFCell cell = row.createCell( (short) 1 );
              cell.setCellValue( "This is a test of merging" );
              Region region = new Region( 1, (short) 1, 4, (short) 4 );
              sheet1.addMergedRegion( region );
          
              // Set the border and border colors.
              final short borderMediumDashed = HSSFCellStyle.BORDER_MEDIUM_DASHED;
              HSSFRegionUtil.setBorderBottom( borderMediumDashed,
                  region, sheet1, wb );
              HSSFRegionUtil.setBorderTop( borderMediumDashed,
                  region, sheet1, wb );
              HSSFRegionUtil.setBorderLeft( borderMediumDashed,
                  region, sheet1, wb );
              HSSFRegionUtil.setBorderRight( borderMediumDashed,
                  region, sheet1, wb );
              HSSFRegionUtil.setBottomBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
              HSSFRegionUtil.setTopBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
              HSSFRegionUtil.setLeftBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
              HSSFRegionUtil.setRightBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
          
              // Shows some usages of HSSFCellUtil
              HSSFCellStyle style = wb.createCellStyle();
              style.setIndention((short)4);
              HSSFCellUtil.createCell(row, 8, "This is the value of the cell", style);
              HSSFCell cell2 = HSSFCellUtil.createCell( row2, 8, "This is the value of the cell");
              HSSFCellUtil.setAlignment(cell2, wb, HSSFCellStyle.ALIGN_CENTER);
          
              // Write out the workbook
              FileOutputStream fileOut = new FileOutputStream( "workbook.xls" );
              wb.write( fileOut );
              fileOut.close();
                              

          Shift rows up or down on a sheet

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("row sheet");
          
              // Create various cells and rows for spreadsheet.
          
              // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
              sheet.shiftRows(5, 10, -5);
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Set a sheet as selected 設置為以選

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("row sheet");
              sheet.setSelected(true);
          
              // Create various cells and rows for spreadsheet.
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Set the zoom magnification設置放大率

          The zoom is expressed as a fraction. For example to express a zoom of 75% use 3 for the numerator and 4 for the denominator.

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet1 = wb.createSheet("new sheet");
              sheet1.setZoom(3,4);   // 75 percent magnification
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Splits and freeze panes

          There are two types of panes you can create; freeze panes and split panes.

          A freeze pane is split by columns and rows. You create a freeze pane using the following mechanism:

          sheet1.createFreezePane( 3, 2, 3, 2 );

          The first two parameters are the columns and rows you wish to split by. The second two parameters indicate the cells that are visible in the bottom right quadrant.

          Split pains appear differently. The split area is divided into four separate work area's. The split occurs at the pixel level and the user is able to adjust the split by dragging it to a new position.

          Split panes are created with the following call:

          sheet2.createSplitPane( 2000, 2000, 0, 0, HSSFSheet.PANE_LOWER_LEFT );

          The first parameter is the x position of the split. This is in 1/20th of a point. A point in this case seems to equate to a pixel. The second parameter is the y position of the split. Again in 1/20th of a point.

          The last parameter indicates which pane currently has the focus. This will be one of HSSFSheet.PANE_LOWER_LEFT, PANE_LOWER_RIGHT, PANE_UPPER_RIGHT or PANE_UPPER_LEFT.

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet1 = wb.createSheet("new sheet");
              HSSFSheet sheet2 = wb.createSheet("second sheet");
              HSSFSheet sheet3 = wb.createSheet("third sheet");
              HSSFSheet sheet4 = wb.createSheet("fourth sheet");
          
              // Freeze just one row
              sheet1.createFreezePane( 0, 1, 0, 1 );
              // Freeze just one column
              sheet2.createFreezePane( 1, 0, 1, 0 );
              // Freeze the columns and rows (forget about scrolling position of the lower right quadrant).
              sheet3.createFreezePane( 2, 2 );
              // Create a split with the lower left side being the active quadrant
              sheet4.createSplitPane( 2000, 2000, 0, 0, HSSFSheet.PANE_LOWER_LEFT );
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Repeating rows and columns

          It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRowsAndColumns() function in the HSSFWorkbook class.

          This function Contains 5 parameters. The first parameter is the index to the sheet (0 = first sheet). The second and third parameters specify the range for the columns to repreat. To stop the columns from repeating pass in -1 as the start and end column. The fourth and fifth parameters specify the range for the rows to repeat. To stop the columns from repeating pass in -1 as the start and end rows.

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet1 = wb.createSheet("new sheet");
              HSSFSheet sheet2 = wb.createSheet("second sheet");
          
              // Set the columns to repeat from column 0 to 2 on the first sheet
              wb.setRepeatingRowsAndColumns(0,0,2,-1,-1);
              // Set the the repeating rows and columns on the second sheet.
              wb.setRepeatingRowsAndColumns(1,4,5,1,2);
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Headers and Footers 頁頭 和 頁腳

          Example is for headers but applies directly to footers.

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet("new sheet");
          
              HSSFHeader header = sheet.getHeader();
              header.setCenter("Center Header");
              header.setLeft("Left Header");
              header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") + 
                              HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic font and size 16");
          
              FileOutputStream fileOut = new FileOutputStream("workbook.xls");
              wb.write(fileOut);
              fileOut.close();
                              

          Drawing Shapes

          POI supports drawing shapes using the Microsoft Office drawing tools. Shapes on a sheet are organized in a hiearchy of groups and and shapes. The top-most shape is the patriarch. This is not visisble on the sheet at all. To start drawing you need to call createPatriarch on the HSSFSheet class. This has the effect erasing any other shape information stored in that sheet. By default POI will leave shape records alone in the sheet unless you make a call to this method.

          To create a shape you have to go through the following steps:

          1. Create the patriarch.
          2. Create an anchor to position the shape on the sheet.
          3. Ask the patriarch to create the shape.
          4. Set the shape type (line, oval, rectangle etc...)
          5. Set any other style details converning the shape. (eg: line thickness, etc...)
              HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
              a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 );
              HSSFSimpleShape shape1 = patriarch.createSimpleShape(a1);
              shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
                              

          Text boxes are created using a different call:

              HSSFTextbox textbox1 = patriarch.createTextbox(
                      new HSSFClientAnchor(0,0,0,0,(short)1,1,(short)2,2));
              textbox1.setString(new HSSFRichTextString("This is a test") );
                              

          It's possible to use different fonts to style parts of the text in the textbox. Here's how:

              HSSFFont font = wb.createFont();
              font.setItalic(true);
              font.setUnderline(HSSFFont.U_DOUBLE);
              HSSFRichTextString string = new HSSFRichTextString("Woo!!!");
              string.applyFont(2,5,font);
              textbox.setString(string );
                              

          Just as can be done manually using Excel, it is possible to group shapes together. This is done by calling createGroup() and then creating the shapes using those groups.

          It's also possible to create groups within groups.

          Warning
          Any group you create should contain at least two other shapes or subgroups.

          Here's how to create a shape group:

              // Create a shape group.
              HSSFShapeGroup group = patriarch.createGroup(
                      new HSSFClientAnchor(0,0,900,200,(short)2,2,(short)2,2));
          
              // Create a couple of lines in the group.
              HSSFSimpleShape shape1 = group.createShape(new HSSFChildAnchor(3,3,500,500));
              shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
              ( (HSSFChildAnchor) shape1.getAnchor() ).setAnchor((short)3,3,500,500);
              HSSFSimpleShape shape2 = group.createShape(new HSSFChildAnchor((short)1,200,400,600));
              shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
                              

          If you're being observant you'll noticed that the shapes that are added to the group use a new type of anchor: the HSSFChildAnchor. What happens is that the created group has it's own coordinate space for shapes that are placed into it. POI defaults this to (0,0,1023,255) but you are able to change it as desired. Here's how:

              myGroup.setCoordinates(10,10,20,20); // top-left, bottom-right
                              

          If you create a group within a group it's also going to have it's own coordinate space.

          Styling Shapes?

          By default shapes can look a little plain. It's possible to apply different styles to the shapes however. The sorts of things that can currently be done are:

          • Change the fill color.
          • Make a shape with no fill color.
          • Change the thickness of the lines.
          • Change the style of the lines. Eg: dashed, dotted.
          • Change the line color.

          Here's an examples of how this is done:

              HSSFSimpleShape s = patriarch.createSimpleShape(a);
              s.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
              s.setLineStyleColor(10,10,10);
              s.setFillColor(90,10,200);
              s.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3);
              s.setLineStyle(HSSFShape.LINESTYLE_DOTSYS);
                              

          Shapes and Graphics2d

          While the native POI shape drawing commands are the recommended way to draw shapes in a shape it's sometimes desirable to use a standard API for compatibility with external libraries. With this in mind we created some wrappers for Graphics and Graphics2d.

          Warning
          It's important to not however before continuing that Graphics2d is a poor match to the capabilities of the Microsoft Office drawing commands. The older Graphics class offers a closer match but is still a square peg in a round hole.

          All Graphics commands are issued into an HSSFShapeGroup. Here's how it's done:

              a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 1, 0 );
              group = patriarch.createGroup( a );
              group.setCoordinates( 0, 0, 80 * 4 , 12 * 23  );
              float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) / (float)Math.abs(group.getY2() - group.getY1());
              g = new EscherGraphics( group, wb, Color.black, verticalPointsPerPixel );
              g2d = new EscherGraphics2d( g );
              drawChemicalStructure( g2d );
                              

          The first thing we do is create the group and set it's coordinates to match what we plan to draw. Next we calculate a reasonable fontSizeMultipler then create the EscherGraphics object. Since what we really want is a Graphics2d object we create an EscherGraphics2d object and pass in the graphics object we created. Finally we call a routine that draws into the EscherGraphics2d object.

          The vertical points per pixel deserves some more explanation. One of the difficulties in converting Graphics calls into escher drawing calls is that Excel does not have the concept of absolute pixel positions. It measures it's cell widths in 'characters' and the cell heights in points. Unfortunately it's not defined exactly what type of character it's measuring. Presumably this is due to the fact that the Excel will be using different fonts on different platforms or even within the same platform.

          Because of this constraint we've had to implement the concept of a verticalPointsPerPixel. This the amount the font should be scaled by when you issue commands such as drawString(). To calculate this value use the follow formula:

              multipler = groupHeightInPoints / heightOfGroup
                              

          The height of the group is calculated fairly simply by calculating the difference between the y coordinates of the bounding box of the shape. The height of the group can be calculated by using a convenience called HSSFClientAnchor.getAnchorHeightInPoints().

          Many of the functions supported by the graphics classes are not complete. Here's some of the functions that are known to work.

          • fillRect()
          • fillOval()
          • drawString()
          • drawOval()
          • drawLine()
          • clearRect()

          Functions that are not supported will return and log a message using the POI logging infrastructure (disabled by default).

          Outlining

          Outlines are great for grouping sections of information together and can be added easily to columns and rows using the POI API. Here's how:

              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet1 = wb.createSheet("new sheet");
          
              sheet1.groupRow( 5, 14 );
              sheet1.groupRow( 7, 14 );
              sheet1.groupRow( 16, 19 );
          
              sheet1.groupColumn( (short)4, (short)7 );
              sheet1.groupColumn( (short)9, (short)12 );
              sheet1.groupColumn( (short)10, (short)11 );
          
              FileOutputStream fileOut = new FileOutputStream(filename);
              wb.write(fileOut);
              fileOut.close();
                              

          To collapse (or expand) an outline use the following calls:

              sheet1.setRowGroupCollapsed( 7, true );
              sheet1.setColumnGroupCollapsed( (short)4, true );
                              

          The row/column you choose should contain an already created group. It can be anywhere within the group.

          Images

          Images are part of the drawing support. To add an image just call createPicture() on the drawing patriarch. At the time of writing the following types are supported:

          • PNG
          • JPG
          • DIB

          It is not currently possible to read existing images and it should be noted that any existing drawings may be erased once you add a image to a sheet.

              // Create the drawing patriarch.  This is the top level container for
              // all shapes. This will clear out any existing shapes for that sheet.
              HSSFPatriarch patriarch = sheet5.createDrawingPatriarch();
          
              HSSFClientAnchor anchor;
              anchor = new HSSFClientAnchor(0,0,0,255,(short)2,2,(short)4,7);
              anchor.setAnchorType( 2 );
              patriarch.createPicture(anchor, loadPicture( "src/resources/logos/logoKarmokar4.png", wb ));
                      

          Named Ranges and Named Cells

          Named Range is a way to refer to a group of cells by a name. Named Cell is a degenerate case of Named Range in that the 'group of cells' contains exactly one cell. You can create as well as refer to cells in a workbook by their named range. When working with Named Ranges, the classes: org.apache.poi.hssf.util.CellReference and & org.apache.poi.hssf.util.AreaReference are used.

          Creating Named Range / Named Cell

              // setup code
              String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
              HSSFWorkbook wb = new HSSFWorkbook();
              HSSFSheet sheet = wb.createSheet(sname);
              sheet.createRow(0).createCell((short) 0).setCellValue(cvalue);
               
              // 1. create named range for a single cell using areareference
              HSSFName namedCell = wb.createName();
              namedCell.setNameName(cname);
              String reference = sname+"!A1:A1"; // area reference
              namedCell.setReference(reference);
              
              // 2. create named range for a single cell using cellreference
              HSSFName namedCell = wb.createName();
              namedCell.setNameName(cname);
              String reference = sname+"!A1"; // cell reference
              namedCell.setReference(reference);
              
              // 3. create named range for an area using AreaReference
              HSSFName namedCell = wb.createName();
              namedCell.setNameName(cname);
              String reference = sname+"!A1:C5"; // area reference
              namedCell.setReference(reference);
              
                      

          Reading from Named Range / Named Cell

              // setup code
              String cname = "TestName";
              HSSFWorkbook wb = getMyWorkbook(); // retrieve workbook
          
              // retrieve the named range
              int namedCellIdx = wb.getNameIndex(cellName);
              HSSFName aNamedCell = wb.getNameAt(namedCellIdx);
              
              // retrieve the cell at the named range and test its contents
              AreaReference aref = new AreaReference(aNamedCell.getReference());
              CellReference[] crefs = aref.getCells();
              for (int i=0; i<crefs.length; i++) {
                  HSSFSheet s = wb.getSheet(crefs[i].getSheetName());
                  HSSFRow r = sheet.getRow(crefs[i].getRow());
                  HSSFCell c = r.getCell(crefs[i].getCol());
                  // extract the cell contents based on cell type etc.
              }
                      
          posted @ 2006-09-14 16:47 brock 閱讀(1061) | 評論 (3)編輯 收藏

          excel 樣式

          // create?a?cell?object? 創建一個元素(行的列)對象
          HSSFCell?cell? = ?row.createCell(column);
          // create?a?cell?style?object 創建一個元素的樣式對象
          HSSFCellStyle?cellStyle? = ?wb.createCellStyle();
          cellStyle.setAlignment(align);?
          cellStyle.setVerticalAlignment(valign);
          // set?cell?border?? 設置元素的邊框
          cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
          cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
          cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
          cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
          // set?foreground?color 設置元素的前景色
          cellStyle.setFillForegroundColor(bgColor);
          cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
          // set?font 設置字體
          cellStyle.setFont(font);
          // set?size
          // set?the?style?of?this?cell? 把樣式加到元素中
          cell.setCellStyle(cellStyle);
          // set?cell&#39;s?charset 設置字符 (中文問題)
          cell.setEncoding(HSSFCell.ENCODING_UTF_16);
          // set?cell?value 改元素賦值
          cell.setCellValue(value);
          從data? 中得到數據
          ArrayList?datacell_list?=?DBToExcel.getSheetDataCol(tableid,k_row,new?DBAgent());
          for(int?k_col=0;k_col<datacell_list.size();k_col++){
            HSSFCell?cell?
          =?row.createCell((short)k_col);
            cell.setEncoding(HSSFCell.ENCODING_UTF_16);

            SheetDataBean?sdb?
          =(SheetDataBean)datacell_list.get(k_col);
          colnum?
          =?sdb.getColnum();

          String?data?
          =?DBToExcel.getSheetCellValue(tableid,k_row,colnum,new?DBAgent());
          //cell.setCellValue(data); 
          打印
          1.
          HSSFCell?c;
          ..
          c.setEncoding(HSSFCell.ENCODING_UTF_16);
          c.setCellValue(
          "測試測試測試測試測試測試測試測試");

          2.
          打印設置
          import?org.apache.poi.hssf.usermodel.HSSFPrintSetup;
          創建打印設置對象
          HSSFPrintSetup?hps?
          =?hs.getPrintSetup();
          設置A4紙
          hps.setPaperSize((
          short)9);?
          將頁面設置為橫向打印模式
          hps.setLandscape(
          true);?
          設置打印頁面為水平居中
          sheet.setHorizontallyCenter(
          true);?
          設置打印頁面為垂直居中
          sheet.setVerticallyCenter(
          true);
          posted @ 2006-09-14 16:24 brock 閱讀(904) | 評論 (1)編輯 收藏

          ?

          // tnsnames.ora
          本地網絡服務名配置 --> 添加 --> 服務名(gis) --> 主機名(電腦名) --
          // 創建表空間
          create?tablespace?tran
          datafile?'D:\Oracle\oradata\orcl\tran.dbf'
          size?10M;
          // 用戶
          create?user?tran?identified?by?tran
          default ?tablespace?tran;

          // 授權成功。
          grant?connect?,resource?to?tran;

          // 連接。
          ?connect?tran / tran

          // 表已創建。
          create?table?test?as?select? * ?from?user_objects;


          // 表空間已刪除
          SQL > ?drop?tablespace?tran
          ??
          2 ??;
          drop?tablespace?tran
          *
          第?
          1 ?行出現錯誤:
          ORA
          - 01549 :?表空間非空,?請使用?INCLUDING?CONTENTS?選項


          SQL
          > ?drop?tablespace?tran?including?contents
          ??
          2 ??;

          表空間已刪除。

          // SQL>?drop?user?tran;


          用戶已刪除。




          // //////////////
          ORACLE應用經驗( 5 ) - 表空間
          二、查看有哪些表空間
          svrmgrl
          > ?SELECT? * ?FROM?DBA_TABLESPACES;
          ?????????SYSTEM???RBS?????TEMP?????TOOLS????USERS
          三、將USERS表空間DROP
          svrmgrl
          > ?ALTER?TABLESPACE?USERS?OFFLINE;
          svrmgrl
          > ?DROP?TABLESPACE?USERS;
          四、查看表空間的空余大小
          svrmgrl
          > ?SELECT?TABLESPACE_NAME,SUM(BYTES) / 1024 / 1024 ?MB?
          ???????????FROM?DBA_FREE_SPACE?GROUP?BY?TABLESPACE_NAME;

          TABLESPACE_NAME???????????????????????MB
          ------------------------------ ? ---------
          DD_DATA????????????????????????
          1136.3672
          DD_IDX?????????????????????????
          787.18164
          JX_DATA????????????????????????
          827.94531
          JX_IDX?????????????????????????
          503.16016
          RBS?????????????????????????????
          371.9668
          SYSTEM?????????????????????????
          457.81445
          TEMP???????????????????????????
          1499.9961
          TOOLS??????????????????????????
          36.462891

          五、查看數據文件放置的路徑
          svrmgrl
          > ?SELECT?TABLESPACE_NAME,BYTES / 1024 / 1024 ?MB,FILE_NAME?
          ?????????FROM?DBA_DATA_FILES;
          TABLESPACE_NAME???????????????????????MB?FILE_NAME
          ------------------------------ ? --------- ? ---------------
          SYSTEM???????????????????????????????
          500 ? / dev / rdrd / drd4
          RBS??????????????????????????????????
          500 ? / dev / rdrd / drd14
          RBS?????????????????????????????????
          1000 ? / dev / rdrd / drd15
          RBS??????????????????????????????????
          500 ? / dev / rdrd / drd32
          TOOLS?????????????????????????????????
          50 ? / dev / rdrd / drd5
          TEMP????????????????????????????????
          1000 ? / dev / rdrd / drd22
          TEMP?????????????????????????????????
          500 ? / dev / rdrd / drd23
          JX_DATA??????????????????????????????
          500 ? / dev / rdrd / drd33

          六、對應SYSTEM表空間有一個回退段,為SYSTEM,另有一些回退段是屬于RBS的,
          ????先將RBS下的回退段都OFFLINE,并DROP,然后將RBS表空間DROP并重新創建,
          ????最后,創建回退段?;赝硕?個,每個大小為RBS
          / 4 ,這個值可以當作OPTIMAL值,
          ????即等于INITIAL
          + NEXT * MAXEXTENTS

          svrmgrl
          > ?ALTER?ROLLBACK?SEGMENT?R01?OFFLINE;
          svrmgrl
          > ?DROP?ROLLBACK?SEGMENT?R01;
          svrmgrl
          > ?alter?tablespace?rbs?offline;
          svrmgrl
          > ?drop?tablespace?rbs;
          svrmgrl
          > ?Create?TABLESPACE? " RBS " ?DATAFILE?
          ?????????'
          / dev / rdrd / rbs01.ora'?SIZE?500M,
          ?????????'
          / dev / rdrd / rbs02.ora'?SIZE?500M;
          svrmgrl
          > ?CREATE?ROLLBACK?SEGMENT? " R01 " ?TABLESPACE? " RBS " ?
          ?????????STORAGE?(?INITIAL?200M?NEXT?2M?OPTIMAL?250M?
          ???????????????????MINEXTENTS?
          2 ?MAXEXTENTS? 25 );

          七、查看回退段及表空間的狀態,若為ONLINE,即結束,為OFFLINE,要ONLINE
          svrmgrl
          > ?select?SEGMENT_NAME,TABLESPACE_NAME,status?from?DBA_ROLLBACK_SEGS;
          svrmgrl
          > ?ALTER?ROLLBACK?SEGMENT?R01?ONLINE;

          八、臨時表空間TEMP,先DROP,再重建。
          svrmgrl
          > ?alter?tablespace?temp?offline;
          svrmgrl
          > ?drop?tablespace?temp;
          svrmgrl
          > ?CREATE?TABLESPACE?temp?DATAFILE?
          ?????????'
          / dev / rdrd / drd22'?SIZE?1000M?storage?(initial?300m?next?20m?
          ?????????minextens?
          2 ?maxextents? 35 ?pctincrease? 0 );

          九、工具表空間TOOLS大小為50M足夠用,系統表空間SYSTEM為100M足夠用。

          十、創建數據表空間:
          ????DD_DATA、DD_IDX、JX_DATA、JX_IDX、SF_DATA、SF_IDX、JF_DATA、JF_IDX

          svrmgrl
          > ?CREATE?TABLESPACE?dd_data?DATAFILE?
          ?????????'
          / dev / rdrd / drd9'?SIZE?1000M,
          ?????????'
          / dev / rdrd / drd10'?SIZE?1000M,
          ?????????'
          / dev / rdrd / drd26'?SIZE?1000M,
          ?????????'
          / dev / rdrd / drd35'?SIZE?1000M,
          ?????????'
          / dev / rdrd / drd42'?SIZE?500M;

          十一、創建用戶
          svrmgrl
          > ?CREATE?USER?ddbh?IDENTIFIED?BY?ddbh?
          ?????????DEFAULT?TABLESPACE?dd_data?
          ?????????TEMPORARY?TABLESPACE?temp
          ?????????QUOTA?UNLIMITED?ON?dd_data?
          ?????????QUOTA?UNLIMITED?ON?dd_idx
          ?????????QUOTA?UNLIMITED?ON?rbs
          ?????????QUOTA?UNLIMITED?ON?temp;

          十二、用戶權限
          svrmgrl
          > ?grant?connect,resources,imp_full_database,exp_full_database,
          ?????????create?public?synonym,drop?public?synonym?to?ddbh;

          ?????若要查看V$SESSION,KILL?SESSION,?DROP?USER,CREATE?USER等,則

          svrmgrl
          > ?grant?select?on?v_$session?to?public;
          svrmgrl
          > ?grant?alter?system,drop?user,create?user?to? " ******* " ;
          posted @ 2006-08-31 14:08 brock 閱讀(322) | 評論 (0)編輯 收藏

          在提到上述的概念之前,首先想說說javascript中函數的隱含參數:arguments

          Arguments

          該對象代表正在執行的函數和調用它的函數的參數。

          [function.]arguments[n]
          參數function :選項。當前正在執行的 Function 對象的名字。 n :選項。要傳遞給 Function 對象的從0開始的參數值索引。
          說明

          Arguments是進行函數調用時,除了指定的參數外,還另外創建的一個隱藏對象。Arguments是一個類似數組但不是數組的對象,說它類似數組是因為其具有數組一樣的訪問性質及方式,可以由arguments[n]來訪問對應的單個參數的值,并擁有數組長度屬性length。還有就是arguments對象存儲的是實際傳遞給函數的參數,而不局限于函數聲明所定義的參數列表,而且不能顯式創建 arguments 對象。arguments 對象只有函數開始時才可用。下邊例子詳細說明了這些性質:


          // arguments?對象的用法。
          function ?ArgTest(a,?b){
          ???
          var ?i,?s? = ? " The?ArgTest?function?expected? "
          ;
          ???
          var ?numargs? = ?arguments.length;????? // ?獲取被傳遞參數的數值。

          ??? var ?expargs? = ?ArgTest.length;??????? // ?獲取期望參數的數值。
          ??? if ?(expargs? < ? 2 )
          ??????s?
          += ?expargs? + ? " ?argument.? "
          ;
          ???
          else

          ??????s?
          += ?expargs? + ? " ?arguments.? " ;
          ???
          if ?(numargs? < ? 2
          )
          ??????s?
          += ?numargs? + ? " ?was?passed. "
          ;
          ???
          else

          ??????s?
          += ?numargs? + ? " ?were?passed. " ;
          ???s?
          += ? " \n\n "

          ???
          for ?(i? = 0 ?;?i? < ?numargs;?i ++ ){?????? // ?獲取參數內容。
          ???s? += ? " ??Arg? " ? + ?i? + ? " ?=? " ? + ?arguments[i]? + ? " \n " ;
          ???}
          ???
          return (s);?????????????????????????? // ?返回參數列表。

          }


          在此添加了一個說明arguments不是數組(Array類)的代碼:

          Array.prototype.selfvalue? = ? 1 ;
          alert(
          new
          ?Array().selfvalue);
          function
          ?testAguments(){
          ????alert(arguments.selfvalue);
          }


          運行代碼你會發現第一個alert顯示1,這表示數組對象擁有selfvalue屬性,值為1,而當你調用函數testAguments時,你會發現顯示的是“undefined”,說明了不是arguments的屬性,即arguments并不是一個數組對象。

          ?caller
          ? 返回一個對函數的引用,該函數調用了當前函數。
          ? functionName.caller
          ? functionName 對象是所執行函數的名稱。
          說明
          對于函數來說,caller屬性只有在函數執行時才有定義。如果函數是由頂層調用的,那么 caller包含的就是 null 。如果在字符串上下文中使用 caller屬性,那么結果和 functionName.toString 一樣,也就是說,顯示的是函數的反編譯文本。
          下面的例子說明了 caller 屬性的用法:

          // ?caller?demo?{
          function ?callerDemo()?{
          ????
          if ?(callerDemo.caller)?{
          ????????
          var ?a = ?callerDemo.caller.toString();
          ????????alert(a);
          ????}?
          else ?{
          ????????alert(
          " this?is?a?top?function " );
          ????}
          }
          function ?handleCaller()?{
          ????callerDemo();
          }


          callee

          ??? 返回正被執行的 Function 對象,也就是所指定的 Function 對象的正文。

          				
          						[function.]arguments.callee
          				
          		

          可選項 function參數是當前正在執行的 Function對象的名稱。

          說明

          callee 屬性的初始值就是正被執行的 Function 對象。

          callee 屬性是 arguments 對象的一個成員,它表示對函數對象本身的引用,這有利于匿名
          函數的遞歸或者保證函數的封裝性,例如下邊示例的遞歸計算1n的自然數之和。而該屬性
          僅當相關函數正在執行時才可用。還有需要注意的是callee擁有length屬性,這個屬性有時候
          用于驗證還是比較好的。arguments.length是實參長度,arguments.callee.length
          形參長度,由此可以判斷調用時形參長度是否和實參長度一致。

          示例

          // callee可以打印其本身
          function ?calleeDemo()?{
          ????alert(arguments.callee);
          }
          // 用于驗證參數
          function ?calleeLengthDemo(arg1,?arg2)?{
          ????
          if ?(arguments.length == arguments.callee.length)?{
          ????????window.alert(
          " 驗證形參和實參長度正確! " );
          ????????
          return ;
          ????}?
          else ?{
          ????????alert(
          " 實參長度: " ? + arguments.length);
          ????????alert(
          " 形參長度:? " ? + arguments.callee.length);
          ????}
          }
          // 遞歸計算
          var ?sum? = ? function (n){
          ??
          if ?(n? <= ? 0 )????????????????????????
          ??
          return ? 1 ;
          ??
          else
          ????
          return ?n?+arguments.callee(n? - ? 1 )
          }

          比較一般的遞歸函數:

          var ?sum? = ? function (n){
          ????
          if ?( 1 == n)? return ? 1 ;
          else ? return ?n? + ?sum?(n - 1 );

          調用時:alert(sum(100));
          其中函數內部包含了對sum自身的引用,函數名僅僅是一個變量名,在函數內部調用sum即相當于調用
          一個全局變量,不能很好的體現出是調用自身,這時使用callee會是一個比較好的方法。

          apply and call

          ?? 它們的作用都是將函數綁定到另外一個對象上去運行,兩者僅在定義參數方式有所區別:

          ??? apply (thisArg,argArray);

          ??? call (thisArg[,arg1,arg2…] ]);

          即所有函數內部的 this 指針都會被賦值為 thisArg ,這可實現將函數作為另外一個對象的方法運行的目的

          apply 的說明

          如果 argArray不是一個有效的數組或者不是 arguments對象,那么將導致一個 TypeError。
          如果沒有提供 argArray
          thisArg 任何一個參數,那么 Global 對象將被用作 thisArg ,
          并且無法被傳遞任何參數。

          call的說明

          call 方法可將一個函數的對象上下文從初始的上下文改變為由 thisArg 指定的新對象。
          如果沒有提供
          thisArg 參數,那么 Global 對象被用作 thisArg

          相關技巧

          應用 call apply 還有一個技巧在里面,就是用 call apply 應用另一個函數(類)以后,當前的
          函數(類)就具備了另一個函數(類)的方法或者是屬性,這也可以稱之為“繼承”??聪旅媸纠?

          // ?繼承的演示
          function ?base()?{
          ????
          this .member? = ? " ?dnnsun_Member " ;
          ????
          this .method? = ? function ()?{
          ????????window.alert(
          this .member);
          ????}
          }
          function ?extend()?{
          ????base.call(
          this );
          ????window.alert(member);
          ????window.alert(
          this .method);
          }


          上面的例子可以看出,通過call之后,extend可以繼承到base的方法和屬性。

          ?

          順便提一下,在 javascript 框架 prototype 里就使用 apply 來創建一個定義類的模式,

          其實現代碼如下:

          var ?Class? = ?{
          ??create:?
          function ()?{
          ????
          return ? function ()?{
          ??????
          this .initialize.apply( this ,?arguments);
          ????}
          ??}
          }

          解析:從代碼看,該對象僅包含一個方法:Create,其返回一個函數,即類。但這也同時是類的
          構造函數,其中調用initialize,而這個方法是在類創建時定義的初始化函數。通過如此途徑,
          就可以實現prototype中的類創建模式

          示例

          var ?vehicle = Class.create();
          vehicle.prototype
          = {
          ????initialize:
          function (type){
          ????????
          this .type = type;
          ????}
          ????showSelf:
          function (){
          ????????alert(
          " this?vehicle?is? " + ? this .type);
          ????}
          }

          var ?moto = new ?vehicle( " Moto " );
          moto.showSelf();


          更詳細的關于prototype信息請到其官方網站查看。


          //下面是一個總合實例
          <script>
          function Point2D(x, y)
          {
          ?this.x = x;
          ?this.y = y;
          ?Point2D.prototype.quadrant = function()
          ?{
          ? if (x > 0 && y > 0) return "I";
          ? else if (x < 0 && y > 0) return "II";
          ? else if (x < 0 && y < 0) return "III";
          ? else if (x > 0 && y < 0) return "IV";
          ? else if (x == 0) return "x-axis";
          ? else if (y == 0) return "y-axis";
          ? else throw new Error();
          ?}
          ?Point2D.prototype.toVector = function()
          ?{
          ? return new Vector2D(x, y);
          ?}
          ?Point2D.prototype.distance = function() //求距離
          ?{
          ? if (arguments.length == 1 && arguments[0] instanceof Point2D)
          ? {
          ?? return this._point_distance.apply(this, arguments);
          ? }
          ? else if (arguments.length == 1 && arguments[0] instanceof Vector2D)
          ? {
          ?? return this._vector_distance.apply(this, arguments);
          ? }
          ? else
          ? {
          ?? throw new Error("Argument Error!");
          ? }
          ?}
          ?Point2D.prototype._point_distance = function(p)? //求兩點之間的距離(函數重載)
          ?{
          ? return (new Vector2D(p,this)).length();
          ?}
          ?Point2D.prototype._vector_distance = function(v)? //求點到向量的距離(函數重載)
          ?{
          ? var v1 = new Vector2D(this, v.start);
          ? var v2 = new Vector2D(this, v.end);

          ? var area = Math.abs(v1.cross(v2));? //平行四邊形面積 = v1 X v2 = |v1v2|sin(v1,v2)
          ?
          ? return area / v.length();?? //平行四邊形面積除以底邊長度即為點到向量的距離
          ?}
          }
          function Vector2D()
          {
          ?if (arguments.length == 2 && arguments[0] instanceof Point2D && arguments[1] instanceof Point2D)
          ?{
          ? _point_point_Vector2D.apply(this, arguments);
          ?}
          ?else if (arguments.length == 2 && !isNaN(arguments[0]) && !isNaN(arguments[1]))
          ?{
          ? _double_double_Vector2D.apply(this, arguments);
          ?}
          ?else if (arguments.length == 4 && !isNaN(arguments[0]) && !isNaN(arguments[1])
          ? && !isNaN(arguments[2]) && !isNaN(arguments[3]))
          ?{
          ? _double_double_double_double_Vector2D.apply(this, arguments);
          ?}
          ?else
          ?{
          ? throw new Error("Argument Error!");
          ?}
          }
          function _point_point_Vector2D(p1, p2)??
          {
          ?this.start = p1;
          ?this.end = p2;
          ?Vector2D.prototype.length = function() //求向量的長度
          ?{
          ? return Math.sqrt(this.pond_x() * this.pond_x() + this.pond_y() * this.pond_y());
          ?}
          ?Vector2D.prototype.pond_x = function() //x方向分量
          ?{
          ? return this.start.x - this.end.x;
          ?}
          ?Vector2D.prototype.pond_y = function()
          ?{
          ? return this.start.y - this.end.y;
          ?}
          ?Vector2D.prototype.cross = function(v)?? //求向量的交積 P1 X P2 = x1y2 - x2y1
          ?{
          ? return this.pond_x() * v.pond_y() - v.pond_x() * this.pond_y();
          ?}
          }
          function _double_double_Vector2D(x,y) //重載構造函數Vector2D
          {
          ?this.pointPairs = new Array();
          ?this.pointPairs[0] = new Point2D(0, 0);
          ?this.pointPairs[1] = new Point2D(x, y);

          ?_point_point_Vector2D.apply(this, this.pointPairs);
          }
          function _double_double_double_double_Vector2D(x1, y1, x2, y2)? //重載構造函數Vector2D
          {
          ?this.pointPairs = new Array();
          ?this.pointPairs[0] = new Point2D(x1, y1);
          ?this.pointPairs[1] = new Point2D(x2, y2);

          ?_point_point_Vector2D.apply(this, this.pointPairs);
          }
          var p1 = new Point2D(0,0);
          var p2 = new Point2D(10,10);
          var v1 = new Vector2D(p1,p2);? //通過兩個點(p1,p2)的方式來構造向量V1
          alert("向量v1長度:"+v1.length());
          var v2 = new Vector2D(0,0,5,5);? //通過四個坐標(x1,y1,x2,y2)的方式來構造向量V2
          alert("向量v2長度:"+v2.length());
          var v3 = new Vector2D(0,10);? //通過指定終點的方式來構造向量V3
          alert("向量v3長度:"+v3.length());
          alert("向量v1與v2的交積:"+v1.cross(v2));? //求V1 X V2 (因為平行,所以結果為0)

          var p3 = new Point2D(10,0);
          alert("點p1與p3的距離:"+p1.distance(p3));
          alert("點p3與向量v1的距離:"+p3.distance(v1));
          </script>

          posted @ 2006-08-31 09:50 brock 閱讀(215) | 評論 (0)編輯 收藏

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "[url]http://www.w3.org/TR/html4/loose.dtd[/url]">
          <html>
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
          <title>test.htm</title>
          <script language="javascript">
          function winopen(){
          window.open("test1.htm");
          }
          </script>
          </head>

          <body>
          <form name="form1" method="post" action="" >
          <input type="submit" name="Submit" value="open" onClick="winopen()">
          <input name="txtTest" type="text" id="txtTest" value="Test">
          </form>
          </body>
          </html>

          =========================
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "[url]http://www.w3.org/TR/html4/loose.dtd[/url]">
          <html>
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
          <title>test1.htm</title>
          <script language="javascript">
          function change(){
          var o=window.opener; //這里可以取得父頁的對象的關鍵(打開者),其它的和操作以看的一樣了
          var txtt=o.document.forms[0].txtTest.value;
          alert(txtt)
          var txt=document.getElementById("text1");
          ???? if (o){
          ???? var otxt=o.document.getElementById("txtTest");
          ???? if(otxt){otxt.value=txt.value;}
          ???? }
          }
          </script>
          </head>

          <body>
          <form name="form1" method="post" action="#" >
          <input name="text1" type="text" id="text1">
          <input name="Change" type="submit" id="Change" value="change" onClick="change()">
          </form>
          </body>
          </html>

          posted @ 2006-08-07 14:43 brock 閱讀(4007) | 評論 (3)編輯 收藏

          Java打印服務API

          http://www.yesky.com/SoftChannel/72342371961929728/20030919/1730057.shtml
          posted @ 2006-07-31 17:33 brock 閱讀(169) | 評論 (0)編輯 收藏

          call方法可改變上下文this指針,類似的方法還有apply,只是調用方式上有些不同

          call 方法
          調用一個對象的一個方法,以另一個對象替換當前對象。

          call([thisObj[,arg1[, arg2[, [,.argN]]]]])

          參數
          thisObj

          可選項。將被用作當前對象的對象。

          arg1, arg2, , argN

          可選項。將被傳遞方法參數序列。

          說明
          call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的對象上下文從初始的上下文改變為由 thisObj 指定的新對象。

          如果沒有提供 thisObj 參數,那么 Global 對象被用作 thisObj。



          function product(name, value){
          ? ?this.name = name;
          ? ?if(value > 1000)
          ? ? ? this.value = 999;
          ? ?else
          ? ? ? this.value = value;
          }

          function prod_dept(name, value, dept){
          ? ?this.dept = dept;
          ? ?product.call(this, name, value);
          }

          prod_dept.prototype = new product();

          // since 5 is less than 100 value is set
          cheese = new prod_dept("feta", 5, "food");

          // since 5000 is above 1000, value will be 999
          car = new prod_dept("honda", 5000, "auto");
          posted @ 2006-07-28 14:28 brock 閱讀(133) | 評論 (0)編輯 收藏

          String realPath = pageContext.getServletContext( ).getRealPath("/");
          ? realPath +?"WEB-INF/classes/"
          posted @ 2006-07-28 09:45 brock 閱讀(174) | 評論 (0)編輯 收藏

          ?

          public ? class ?SignOnFilter? implements ?Filter {
          ?
          private ? static ? final ?String?RedirectURL = " redirectURL " ;
          ?
          private ?String?redirectURL = " index.htm " ;

          ?
          public ? void ?init(FilterConfig?config)? throws ?ServletException? {
          ???String?url?
          = config.getInitParameter(RedirectURL);
          ???
          if ?((url != null ) && ( ! url.equals( "" ))) {
          ????redirectURL?
          = url;
          ???}

          ?}

          ?
          ?
          public ?? void ?doFilter(ServletRequest?request,?ServletResponse??response,?FilterChain?chain)
          ????
          throws ?IOException,?ServletException? {
          ??HttpServletRequest?req?
          = (HttpServletRequest)request;
          ??LogInfo?logInfo?
          = (LogInfo)req.getSession().getAttribute(uConst.logInfo);
          ??
          if ?(logInfo? == ? null ) {
          ???HttpServletResponse?resp
          = (HttpServletResponse)response;
          ???req.getRequestDispatcher(redirectURL).forward(req,resp);
          ??}
          else {
          ???chain.doFilter(request,response);
          ??}

          ???}


          ?
          public ? void ?destroy()? {
          ?
          ????}

          ?
          }

          posted @ 2006-07-27 15:21 brock 閱讀(124) | 評論 (0)編輯 收藏

          public class SignonFilter implements Filter
          {
          String LOGIN_PAGE="login.jsp";
          protected FilterConfig filterConfig;

          //過濾處理的方法
          public void doFilter(final ServletRequest req,final ServletResponse res,FilterChain chain)throws IOException,ServletException
          {
          HttpServletRequest hreq = (HttpServletRequest)req;
          HttpServletResponse hres = (HttpServletResponse)res;
          HttpSession session = hreq.getSession();
          String isLogin="";
          try
          {
          isLogin=(String)session.getAttribute("isLogin");
          System.out.print(isLogin);
          if(isLogin!=null&&isLogin.equals("true"))
          {
          System.out.println("在SignonFilter中驗證通過");
          //驗證成功,繼續處理
          chain.doFilter(req,res);
          }
          else
          {
          //驗證不成功,讓用戶登錄。
          hres.sendRedirect("login.jsp");
          System.out.println("被SignonFilter攔截一個未認證的請求");
          }

          }
          catch(Exception e)
          {
          e.printStackTrace();
          }

          }

          public void setFilterConfig(final FilterConfig filterConfig)
          {
          this.filterConfig=filterConfig;
          }

          //銷毀過濾器
          public void destroy()
          {
          this.filterConfig=null;
          }
          /**
          *初始化過濾器,和一般的Servlet一樣,它也可以獲得初始參數。
          */
          public void init(FilterConfig config) throws ServletException {
          this.filterConfig = config;
          }

          }


          posted @ 2006-07-27 15:19 brock 閱讀(1394) | 評論 (1)編輯 收藏

          僅列出標題
          共15頁: First 上一頁 7 8 9 10 11 12 13 14 15 下一頁 
          主站蜘蛛池模板: 五常市| 合川市| 威宁| 泰和县| 罗江县| 高密市| 深州市| 常宁市| 潍坊市| 印江| 呼伦贝尔市| 友谊县| 周宁县| 孝感市| 蒙山县| 察雅县| 剑河县| 南雄市| 贺州市| 阳东县| 长泰县| 涿鹿县| 乐业县| 佳木斯市| 中方县| 古田县| 巴里| 南阳市| 铁岭县| 望都县| 莲花县| 西乌| 瑞丽市| 富顺县| 改则县| 南涧| 宝兴县| 景洪市| 云安县| 潼南县| 冷水江市|