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 阅读(1038) | 评论 (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 阅读(887) | 评论 (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并重新创建,
    最后,创建回退段。回退段4个,每个大小为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 阅读(318) | 评论 (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 阅读(210) | 评论 (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 阅读(3999) | 评论 (3)编辑 收藏

Java打印服务API

http://www.yesky.com/SoftChannel/72342371961929728/20030919/1730057.shtml
posted @ 2006-07-31 17:33 brock 阅读(165) | 评论 (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 阅读(130) | 评论 (0)编辑 收藏

String realPath = pageContext.getServletContext( ).getRealPath("/");
  realPath + "WEB-INF/classes/"
posted @ 2006-07-28 09:45 brock 阅读(171) | 评论 (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 阅读(120) | 评论 (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 阅读(1386) | 评论 (1)编辑 收藏

仅列出标题
共15页: First 上一页 7 8 9 10 11 12 13 14 15 下一页