ï»??xml version="1.0" encoding="utf-8" standalone="yes"?>97超碰在线免费,久久精品中文字幕,亚洲午夜精品在线http://www.aygfsteel.com/brock/category/15415.htmlzh-cnWed, 28 Feb 2007 19:53:25 GMTWed, 28 Feb 2007 19:53:25 GMT60excel poi 处理2http://www.aygfsteel.com/brock/archive/2006/09/19/70548.htmlbrockbrockTue, 19 Sep 2006 07:59:00 GMThttp://www.aygfsteel.com/brock/archive/2006/09/19/70548.htmlhttp://www.aygfsteel.com/brock/comments/70548.htmlhttp://www.aygfsteel.com/brock/archive/2006/09/19/70548.html#Feedback0http://www.aygfsteel.com/brock/comments/commentRss/70548.htmlhttp://www.aygfsteel.com/brock/services/trackbacks/70548.html 在导出数据生成excelæ—Óž¼Œå®šä¹‰excelå•å…ƒæ ¼æ ¼å¼äØ“æ–‡æœ¬ã€?br />最好拿你的导出代码贴出来看看,主要是生成excel时代ç ?br />
--------------------------------------------------------------------------------

参考一�
<% @ page contentType = " text/html; charset=gb2312 " %>
<% @ page  import = " java.io.* " %>
<% @ page  import = " org.apache.poi.hssf.util.HSSFColor " %>
<% @ page  import = " org.apache.poi.hssf.util.Region " %>
<% @ page  import = " org.apache.poi.hssf.usermodel.* " %>
<%
// 初始åŒ?br /> // 工作½?/span>
HSSFWorkbook wb = new  HSSFWorkbook();
// 工作�/span>
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(
0 , " Excel演示! " ,HSSFWorkbook.ENCODING_UTF_16);
// 准备完成
// 建样�br /> // 标题�/span>
HSSFFont font_Header = wb.createFont();
font_Header.setFontName(
" headerFont " );
font_Header.setFontHeightInPoints((
short ) 12 );
HSSFCellStyle cellStyle_Header
= wb.createCellStyle();
cellStyle_Header.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle_Header.setFont(font_Header);
// 通用�/span>
HSSFCellStyle cellStyle_Normal = wb.createCellStyle();
cellStyle_Normal.setAlignment(HSSFCellStyle.ALIGN_LEFT);
// cellStyle_Normal.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// cellStyle_Normal.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cellStyle_Normal.setBorderRight(HSSFCellStyle.BORDER_THIN);
// cellStyle_Normal.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 表格�/span>
HSSFCellStyle cellStyle_Column = wb.createCellStyle();
cellStyle_Column.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle_Column.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle_Column.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle_Column.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle_Column.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle_Column.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle_Column.setFillPattern(HSSFCellStyle.BIG_SPOTS);
cellStyle_Column.setFillBackgroundColor((
short )HSSFColor.WHITE.index);
cellStyle_Column.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
// 数据�/span>
HSSFCellStyle cellStyle_Cell = wb.createCellStyle();
cellStyle_Cell.setAlignment(HSSFCellStyle.ALIGN_LEFT);
cellStyle_Cell.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle_Cell.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle_Cell.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle_Cell.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle_Cell.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle_Cell.setWrapText(
true );
// 样式¾l“束
// ¾|®æ ‡é¢?/span>
HSSFRow row = sheet.createRow(( short ) 0 );
HSSFCell cell
= row.createCell(( short ) 0 );
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue(
" Excel演示! " );
sheet.addMergedRegion(
new  Region( 0 ,( short ) 0 , 0 ,( short ) 5 ));
cell.setCellStyle(cellStyle_Header);
// 完成标题
// 行信�/span>
row = sheet.createRow(( short ) 1 );
cell
= row.createCell(( short ) 0 );
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue(
" FieldName " );
cell.setCellStyle(cellStyle_Normal);
cell
= row.createCell(( short ) 1 );
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue(
" FieldValue " );
sheet.addMergedRegion(
new  Region( 1 ,( short ) 1 , 1 ,( short ) 2 ));
cell.setCellStyle(cellStyle_Normal);
cell
= row.createCell(( short ) 3 );
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue(
" FieldName " );
cell.setCellStyle(cellStyle_Normal);
cell
= row.createCell(( short ) 4 );
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue(
" FieldValue " );
sheet.addMergedRegion(
new  Region( 1 ,( short ) 4 , 1 ,( short ) 5 ));
cell.setCellStyle(cellStyle_Normal);
// 表数�/span>
for ( int  mIndex = 2 ;mIndex < 10 ;mIndex ++ )
{
row
= sheet.createRow(( short )mIndex);
for ( int  nIndex = 0 ;nIndex < 6 ;nIndex ++ )
{
cell
= row.createCell(( short )nIndex);
cell.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
cell.setCellValue(
" 00.00 " );
cell.setCellStyle(cellStyle_Cell);
}

}

// 全局�/span>
sheet.setHorizontallyCenter( true );
for ( int  kIndex = 0 ;kIndex < 10 ;kIndex ++ )
{
sheet.setColumnWidth((
short )kIndex,( short ) 4500 );
}

sheet.setMargin(HSSFSheet.BottomMargin,(
double ) 0.5 );
sheet.setMargin(HSSFSheet.LeftMargin,(
double ) 0.1 );
sheet.setMargin(HSSFSheet.RightMargin,(
double ) 0.1 );
sheet.setMargin(HSSFSheet.TopMargin,(
double ) 0.5 );
// 调整¾l“束
// 输出Excel
OutputStream outData = null ;
outData
= response.getOutputStream();
response.setContentType(
" application/vnd.ms-excel " );
wb.write(outData);
outData.flush();
response.flushBuffer();
// 完成
%>

]]>
Busy Developers' Guide to HSSF Features (说明�http://www.aygfsteel.com/brock/archive/2006/09/14/69688.htmlbrockbrockThu, 14 Sep 2006 08:47:00 GMThttp://www.aygfsteel.com/brock/archive/2006/09/14/69688.htmlhttp://www.aygfsteel.com/brock/comments/69688.htmlhttp://www.aygfsteel.com/brock/archive/2006/09/14/69688.html#Feedback2http://www.aygfsteel.com/brock/comments/commentRss/69688.htmlhttp://www.aygfsteel.com/brock/services/trackbacks/69688.html

Features

New Workbook

    //创徏新的Excel 工作½?br />    HSSFWorkbook wb = new HSSFWorkbook();
//new 一个FileOutputStream FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    //写入‹¹? wb.write(fileOut); fileOut.close();

New Sheet

    HSSFWorkbook wb = new HSSFWorkbook();
  // å¦‚è¦æ–°å¾ä¸€åäØ“"效益指标"的工作表åQŒå…¶è¯­å¥ä¸ºï¼š
 // 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是è“v始行 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.
创徏单元æ ég¹Ÿå¯ä»¥ä¸€è¡Œä»£ç ? 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不同¾cÕdž‹çš„单元格一起工ä½?/h2>

    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½Cø™Œƒä¸åŒçš„对齐选项

    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 åˆåÆˆå•å…ƒæ ?/h2>

    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 自定义颜�/h2>

    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  è¯Õd’Œ 重写工作½?/h2>

    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   一™åµä¸­æ˜¾è§†åˆé€‚的工作è¡?/h2>

    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 讄¡½®æ‰“印åŒ?/h2>

    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  行用方便的方�/h2>

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 讄¡½®ä¸ÞZ»¥é€?/h2>

    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讄¡½®æ”‘Ö¤§çŽ?/h2>

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.
    }
            


]]>
excel 处理 Poihttp://www.aygfsteel.com/brock/archive/2006/09/14/69674.htmlbrockbrockThu, 14 Sep 2006 08:24:00 GMThttp://www.aygfsteel.com/brock/archive/2006/09/14/69674.htmlhttp://www.aygfsteel.com/brock/comments/69674.htmlhttp://www.aygfsteel.com/brock/archive/2006/09/14/69674.html#Feedback0http://www.aygfsteel.com/brock/comments/commentRss/69674.htmlhttp://www.aygfsteel.com/brock/services/trackbacks/69674.htmlexcel 样式

// 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   讄¡½®å…ƒç´ çš„è¾¹æ¡?/span>
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 改元素赋�/span>
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¾U?br />hps.setPaperSize((
short)9); 
ž®†é¡µé¢è®¾¾|®äؓ横向打印模式
hps.setLandscape(
true); 
讄¡½®æ‰“印™åµé¢ä¸ºæ°´òq›_±…ä¸?br />sheet.setHorizontallyCenter(
true); 
讄¡½®æ‰“印™åµé¢ä¸ºåž‚ç›´å±…ä¸?br />sheet.setVerticallyCenter(
true);


]]>
利用POIž®†æ•°æ®è¡¨å¯¼å…¥Excel http://www.aygfsteel.com/brock/archive/2006/07/26/60186.htmlbrockbrockWed, 26 Jul 2006 07:30:00 GMThttp://www.aygfsteel.com/brock/archive/2006/07/26/60186.htmlhttp://www.aygfsteel.com/brock/comments/60186.htmlhttp://www.aygfsteel.com/brock/archive/2006/07/26/60186.html#Feedback0http://www.aygfsteel.com/brock/comments/commentRss/60186.htmlhttp://www.aygfsteel.com/brock/services/trackbacks/60186.html
  • /*
  •  * QuickExcel.java
  •  * 作者:杨庆æˆ?/font>
  •  * Created on 2004òq?1æœ?2æ—? 下午4:05
  •  * 在实际应用中¾lå¸¸è¦å°†æ•°æ®åº“中的表导入Excel
  •  * 本äh在Apacheçš„POI基础上写了一个简单的¾c?/font>
  •  *Â æœ‰ä¸å½“æŒ‡å‡ø™¯·æŒ‡æ­£åQŒè°¢è°¢ï¼
  •  * 
  •  */
  • package  yqc.poi;
  • import  java.sql.*;
  • import  java.util.*;
  • import  java.io.*;
  • import  java.io.ByteArrayInputStream;
  • import  java.io.FileInputStream;
  • import  java.io.FileOutputStream;
  • import  java.io.IOException;
  • import  org.apache.poi.hssf.usermodel.*;
  • import  org.apache.poi.poifs.filesystem.POIFSFileSystem;
  • import  org.apache.poi.hssf.record.*;
  • import  org.apache.poi.hssf.model.*;
  • import  org.apache.poi.hssf.usermodel.*;
  • import  org.apache.poi.hssf.util.*;import yqc.sql.*;
  • /**
  •  *
  •  * @author  Administrator
  •  */
  • public  class QuickExcel {
  •     
  •     /** Creates a new instance of QuickExcel */
  •     private QuickExcel(String file){
  •         _file=file;
  •     }
  •     
  •     private void open()throws IOException{
  •         InputStream stream = null;
  •         Record[] records = null;
  •         POIFSFileSystem fs =
  •             new POIFSFileSystem(new FileInputStream(_file));
  •         _wb = new HSSFWorkbook(fs);
  •     }
  •     
  •     private void create(){
  •         _wb=new HSSFWorkbook();
  •     }
  •     
  •     public static QuickExcel newInstance (String file){
  •         QuickExcel qe=new QuickExcel(file);
  •         qe.create();
  •         return qe;
  •     }
  •     
  •     public static QuickExcel openInstance(String file) throws IOException {
  •         QuickExcel qe=new QuickExcel(file);
  •         qe.open();
  •         return qe;
  •     }
  •     
  •     public void close(){
  •         try{
  •             FileOutputStream fileOut = new FileOutputStream(_file);
  •             _wb.write(fileOut);//把Workbook对象输出到文件workbook.xlsä¸?/font>
  •             fileOut.close();
  •         }
  •         catch (Exception ex){
  •             System.out.println(ex.getMessage());
  •         }
  •     }
  •     
  •     private void removeSheet(String sheetName){
  •         int i=_wb.getSheetIndex("sheetName");
  •         if (i>=0) _wb.removeSheetAt(i);
  •     }
  •     
  •     public int fillSheet (ResultSet rs,String sheetName)throws SQLException {
  •         HSSFSheet st= _wb.createSheet(sheetName);
  •         ResultSetMetaData rsmd= rs.getMetaData();
  •         int index=0;
  •         int result=0;
  •         HSSFRow row=st.createRow(index++);
  •         for(int i=1;i<=rsmd.getColumnCount();++i){
  •             HSSFCell cell=row.createCell((short)(i-1));
  •             cell.setCellValue(rsmd.getColumnName(i));
  •         }
  •         while(rs.next()) {
  •             result++;
  •             row=st.createRow(index++);
  •             for(int i=1;i<=rsmd.getColumnCount();++i){
  •                 HSSFCell cell=row.createCell((short)(i-1));
  •                 cell.setEncoding(cell.ENCODING_UTF_16);
  •                 cell.setCellValue(rs.getString(i));
  •             }
  •         }
  •         return result;
  • }
  •     
  •     public static void main(String[] args){
  •         try{
  •             QuickConnection qc=new MssqlConnection("jdbc:microsoft:sqlserver://192.168.0.100:1433;DatabaseName=ls");
  •             QuickExcel qe=QuickExcel.newInstance("a.xls");
  •             qc.connect();
  •             String sql="select * from ls.dbo.radio1_emcee";
  •             ResultSet rs=qc.getStatement().executeQuery(sql);
  •             qe.fillSheet(rs,"MT");
  •             qe.close();
  •             qe=QuickExcel.openInstance("a.xls");
  •             qe.fillSheet(rs,"MO");
  •             qe.close();
  •             qc.close();
  •         }
  •         catch (SQLException ex){
  •             System.out.println(ex.getMessage());
  •         }
  •         catch (IOException ex){
  •             System.out.println(ex.getMessage());
  •         }
  •     }
  •     
  •     HSSFWorkbook _wb;
  •     String _file="new.xls";
  • }


  • ]]>
    ¾U¯javaçš„Excel解决æ–ÒŽ¡ˆhttp://www.aygfsteel.com/brock/archive/2006/07/26/60185.htmlbrockbrockWed, 26 Jul 2006 07:29:00 GMThttp://www.aygfsteel.com/brock/archive/2006/07/26/60185.htmlhttp://www.aygfsteel.com/brock/comments/60185.htmlhttp://www.aygfsteel.com/brock/archive/2006/07/26/60185.html#Feedback0http://www.aygfsteel.com/brock/comments/commentRss/60185.htmlhttp://www.aygfsteel.com/brock/services/trackbacks/60185.html

    摘要:

    Apacheçš„Jakata™å¹ç›®çš„POI子项目,目标是处理ole2对象。目前比较成熟的是HSSF接口åQŒå¤„理MS ExcelåQ?7-2002åQ‰å¯¹è±?
    å¾®èÊY在桌面系¾lŸä¸Šçš„æˆåŠŸï¼Œä»¤æˆ‘ä»¬ä¸å¾—ä¸å¤§é‡ä½¿ç”¨å®ƒçš„åŠžå…¬äº§å“åQŒå¦‚åQšWordåQŒExcel。时至今日,它的源代码仍然不公开已封锁了我们的进一步应用和开发。然而在要求更高的服务器领域åQŒå¾®è½¯æœ¬íw«çš„产品¿UÀL¤æ€§ä¸å¥½ï¼ŒÂ Â 
    性能不佳。在我们实际的开发中åQŒè¡¨çŽ°å±‚çš„è§£å†Ïx–¹æ¡ˆè™½ç„¶æœ‰å¤šæ ·åQŒä½†æ˜¯Ie‹¹è§ˆå™¨å·²æˆäؓ最多äh使用的浏览器åQŒå› ä¸ºå¤§å®‰™ƒ½ç”¨Windows。在企业办公¾pȝ»Ÿä¸­ï¼Œå¸¸å¸¸æœ‰å®¢æˆ¯‚¿™æ ·å­è¦æ±‚åQšä½ è¦æŠŠæˆ‘们的报表直接用Excel打开。或者是åQšæˆ‘ä»¬å·²¾lä¹ æƒ¯ç”¨Excel打印。这样子如果ç”?net开发是没有问题的,但是有j2ee˜q™ä¸ªæ¯?net更有前途的开攑ּçš„开发环境,éšùN“æˆ‘äØ“äº†è§£å†Ïx‰“印的要求åŽÕd¦å†™å®¢æˆïL«¯çš„æŽ§ä»Óž¼Ÿæˆ–者在服务器端使用本地代码åQŸç¬¬ä¸€¿Uæ–¹æ¡ˆçš„问题是关键数据的处理有时候不能在客户端做åQŒç¬¬2¿Uæ–¹æ¡ˆçš„问题是牺牲了代码的可¿UÀL¤æ€§å’Œ½E›_®šæ€§ã€‚如果让客户端只负责处理生成好的报表åQŒé‚£ž®†æ˜¯ä¸€¿Uè¯±äººçš„选择ã€?br />
    Apacheçš„Jakata™å¹ç›®çš„POI子项目,目标是处理ole2对象。目前比较成熟的是HSSF接口åQŒå¤„理MS ExcelåQ?7-2002åQ‰å¯¹è±¡ã€‚它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象åQŒä½ å¯ä»¥æŽ§åˆ¶ä¸€äº›å±žæ€§å¦‚sheet,cell½{‰ç­‰ã€‚这是一个年è½Èš„™å¹ç›®åQŒæ‰€ä»¥è±¡HDF˜q™æ ·ç›´æŽ¥æ”¯æŒWord对象的好东西仍然在设计中。其它支持word格式的纯javaæ–ÒŽ¡ˆ˜q˜æœ‰itextåQŒä¸˜q‡ä¹Ÿæ˜¯ä»åœ¨å¥‹æ–—中。但是HSSF已经成熟到能够和­‘›_¤Ÿæˆ‘ä»¬ä½¿ç”¨äº†ã€‚å¦å¤–ï¼Œæ— é”¡æ°æ€¸­Office的实现方案也是纯java的解å†Ïx–¹æ¡ˆï¼Œä¸è¿‡é‚£ä¹Ÿæ˜¯å®Œå…¨å•†ä¸šçš„产品åQŒåƈ不是公开代码™å¹ç›®ã€‚其实,从开发历史的角度è®ÔŒ¼Œåœ?0òq´ä»£ä¸­æœŸstarOffice的原作者在德国成立了StarOffice suite公司åQŒç„¶åŽåˆ°1999òq´å¤å¤©starOffice被sunæ”¶è´­åQŒå†åˆ?000òq?月starOffice5.2的发布;òq¶ä¸”从starOffice6.0开始,starOffice建立在OpenOfficeçš„api的基¼‹€ä¸Šï¼Œ˜q™ä¸ªå…¬å¼€ä»£ç çš„office™å¹ç›®å·²ç»˜q›è¡Œäº†å¾ˆé•¿çš„æ—‰™—´ã€‚虽焉™‚£æ˜¯ç”±C++写的åQŒä½†æ˜¯POI的代码部分也是由openOffice改过来的。所以,应该对POI充满­‘›_¤Ÿçš„信心。国内已¾læœ‰éƒ¨åˆ†å…¬å¸åœ¨ä»–们的办公自动化等Web™å¹ç›®ä¸­ä‹É用poi了,如日恒的iofficeåQŒæ“væ³°çš„HTOffice½{‰ã€?br />
    java当初把核心处理设成UnicodeåQŒå¸¦æ¥çš„好处是另代码适应了多语言环境。然而由于老外的英语只æœ?6个字母,有些情况下,一些程序员ç”?位的byte处理åQŒä¸€ä¸å°å¿ƒå°±åŽÀLŽ‰äº†CJK的高位。或者是ç”׃ºŽä¹ æƒ¯åœ¨ç¨‹åºä¸­é‡‡ç”¨¼‹¬ç¼–码,˜q˜æœ‰å¤šç§åŽŸå› åQŒä‹É得许多java应用在CJK的处理上很烦恹{€‚还好在POI HSSF中考虑到这个问题,可以讄¡½®encoding为双字节ã€?br />
    POI可以到www.apache.org下蝲到。编译好的jar主要有这æ ?个:poiåŒ?poi BrowseråŒ?poi hdfåŒ?poi hssf例程包。实际运行时åQŒéœ€è¦æœ‰poi包就可以了。如果用Jakarta ant¾~–译和运行,下蝲apache Jakarta POIçš„release中的src包,它里面已¾läؓ你生成好了buildæ–‡äšg了。只要运行antž®±å¯ä»¥äº†(ant 的安装和使用在此不说äº?。如果是用Jbuilder ˜qè¡ŒåQŒè¯·åœ¨æ–°å»ºçš„™å¹ç›®ä¸­åŠ å…¥poi包。以Jbuilder6ä¸ÞZ¾‹åQŒé€‰æ‹©Tools菜单™å¹çš„config libraries...选项åQŒæ–°å»ÞZ¸€ä¸ªlib。在弹出的菜单中选择poi包,如这个jakarta-poi-1.5.1-final-20020820.jaråQŒæŠŠpoiæ·ÕdŠ åˆ°jbuilder中。然后,右键点击你的™å¹ç›®åQŒåœ¨projectçš„properties菜单中pathçš„required Libraries中,点addåQŒæ·»åŠ åˆšæ‰åŠ å…¥åˆ°jbuilder中的poiåˆîC½ çŽ°åœ¨çš„é¡¹ç›®ä¸­ã€‚å¦‚æžœä½ ä»…ä»…æ˜¯äØ“äº†ç†Ÿæ‚‰POI hssfçš„ä‹É用,可以直接看POIçš„samples包中的源代码åQŒåƈ且运行它。hssf的各¿Uå¯¹è±¡éƒ½æœ‰ä¾‹½E‹çš„介绍。hssf提供的例½E‹åœ¨org.apache.poi.hssf.usermodel.examples包中åQŒå…±æœ?4个,生成的目标xls都是workbook.xls。如果你想看更多的例½E‹ï¼Œå¯ä»¥å‚考hssfçš„Junit test casesåQŒåœ¨poi的包的源代码中有。hssf都有‹¹‹è¯•代码ã€?br />
    ˜q™é‡Œåªå¯¹éƒ¨åˆ†ä¾‹ç¨‹çš„实现做介绍ã€?br />
    HSSF提供¾l™ç”¨æˆ·ä‹É用的对象在org.apache.poi.hssf.usermodel包中,主要部分包括Excell对象åQŒæ ·å¼å’Œæ ¼å¼åQŒè¿˜æœ‰è¾…助操作。有以下几种对象åQ?br />
    HSSFWorkbook excell的文档对�br />
    HSSFSheet excell的表�br />
    HSSFRow excell的行

    HSSFCell excell的格子单�br />
    HSSFFont excell字体

    HSSFName 名称

    HSSFDataFormat 日期格式

    在poi1.7中才有以ä¸?™å¹ï¼š

    HSSFHeader sheet�br />
    HSSFFooter sheetž®?br />
    和这个样�br />
    HSSFCellStyle cell样式

    辅助操作包括

    HSSFDateUtil 日期

    HSSFPrintSetup 打印

    HSSFErrorConstants 错误信息�br />
    仔细看org.apache.poi.hssf包的¾l“æž„åQŒä¸éš‘֏‘现HSSF的内部实现遵循的是MVC模型ã€?br />
    ˜q™é‡Œæˆ‘用Rose把org.apache.poi.hssf.usermodelåŒ…ä¸­çš„å¯¹è±¡åå‘å¯¼å…¥åÆˆæ ÒŽ®ç›æ€º’关系作了整理åQŒè¯¦è§ä¸‹é¢ä¸¤å›¾ï¼š

      IMG ../upload/article/a2005512101549.jpg[/IMG]

    � 基本对象

    从中不难可以发现每一个基本对象都兌™”了一个Record对象。Record对象是一个参考Office格式的相兌™®°å½•ã€?br />
       IMG ../upload/article/2005512101631.jpg[/IMG]


    å›? HSSFWorkbook

    HSSFWorkbookåÏx˜¯ä¸€ä¸ªExcell对象。这òq…类图体现的是HSSFWorkbookå’ŒåŸºæœ¬å¯¹è±¡çš„ç›æ€º’关系。可见,许多对象中也建立了Workbook的引用。还需要注意的是在HSSFWorkbookå’ŒHSSFSheet中徏立了log机制POILoggeråQŒè€Œä¸”POILogger也是使用apache Log4J实现的ã€?br />
    先看poiçš„examples包中提供的最½Ž€å•的例子åQŒå¾ç«‹ä¸€ä¸ªç©ºxlsæ–‡äšgã€?br />
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;

    import java.io.FileOutputStream;

    import java.io.IOException;

    public class NewWorkbook

    {

    public static void main(String[] args)

    throws IOException

    {

    HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象

    FileOutputStream fileOut = new FileOutputStream("workbook.xls");

    wb.write(fileOut);//把Workbook对象输出到文件workbook.xls�br />
    fileOut.close();

    }

    }

    通过˜q™ä¸ªä¾‹å­åQŒæˆ‘们徏立的是一个空白的xlsæ–‡äšgåQˆä¸æ˜¯ç©ºæ–‡äšgåQ‰ã€‚在此基¼‹€ä¸Šï¼Œæˆ‘们可以˜q›ä¸€æ­¥çœ‹å…¶å®ƒçš„例子ã€?br />

    import org.apache.poi.hssf.usermodel.*;

    import java.io.FileOutputStream;

    import java.io.IOException;

    public class CreateCells

    {

    public static void main(String[] args)

    throws IOException

    {

    HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象

    HSSFSheet sheet = wb.createSheet("new sheet");//建立新的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 value in it.

    HSSFCell cell = row.createCell((short)0);//建立新cell

    cell.setCellValue(1);//讄¡½®cell的整数类型的å€?br />

    // Or do it on one line.

    row.createCell((short)1).setCellValue(1.2);//讄¡½®cell‹¹®ç‚¹¾cÕdž‹çš„å€?br />
    row.createCell((short)2).setCellValue("test");//讄¡½®cell字符¾cÕdž‹çš„å€?br />
    row.createCell((short)3).setCellValue(true);//讄¡½®cell布尔¾cÕdž‹çš„å€?

    HSSFCellStyle cellStyle = wb.createCellStyle();//建立新的cell样式

    cellStyle.setDataFormat(HSSFDataFormat.getFormat("m/d/yy h:mm"));//讄¡½®cell样式为定制的日期格式

    HSSFCell dCell =row.createCell((short)4);

    dCell.setCellValue(new Date());//讄¡½®cell为日期类型的å€?br />
    dCell.setCellStyle(cellStyle); //讄¡½®è¯¥cell日期的显½Cºæ ¼å¼?br />
    HSSFCell csCell =row.createCell((short)5);

    csCell.setEncoding(HSSFCell.ENCODING_UTF_16);//讄¡½®cell¾~–码解决中文高位字节截断

    csCell.setCellValue("中文‹¹‹è¯•_Chinese Words Test");//讄¡½®ä¸­è¥¿æ–‡ç»“合字½W¦ä¸²

    row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR);//建立错误cell


    // Write the output to a file

    FileOutputStream fileOut = new FileOutputStream("workbook.xls");

    wb.write(fileOut);

    fileOut.close();

    }

    }

    我稍微修改了原来的examples包中的CreateCells¾cÕd†™äº†ä¸Šé¢çš„功能‹¹‹è¯•¾c…R€‚通过˜q™ä¸ªä¾‹å­åQŒæˆ‘们可以清楚的看到xlsæ–‡äšg从大到小包括了HSSFWorkbook HSSFSheet HSSFRow HSSFCell˜q™æ ·å‡ ä¸ªå¯¹è±¡ã€‚我们可以在cell中设¾|®å„¿Uç±»åž‹çš„倹{€‚尤其要注意的是如果你想正确的显½Cºéž‹Æ§ç¾Žçš„å­—½W¦æ—¶åQŒå°¤å…¶è±¡ä¸­æ—¥éŸ©è¿™æ ïLš„语言åQŒå¿…™å»è®¾¾|®ç¼–ç äØ“16位的åÏx˜¯HSSFCell.ENCODING_UTF_16åQŒæ‰èƒ½ä¿è¯å­—½W¦çš„é«?位不被截断而引èµïL¼–码失真åÅžæˆäØ•ç ã€?br />
    å…¶ä»–‹¹‹è¯•可以通过参考examples包中的测试例子掌握poi的详¾l†ç”¨æ³•,包括字体的设¾|®ï¼Œcell大小和低¾U¹çš„讄¡½®½{‰ã€‚需要注意的是POI是一个仍然在完善中的公开代码的项目,所以有些功能正在不断的扩充。如HSSFSheetçš„getFooter() getHeader()å’ŒsetFooter(HSSFFooter hsf) setHeader(HSSFHeader hsh)是在POI1.7中才有的åQŒè€ŒPOI1.5中就没有。运行测试熟悉代码或者ä‹É用它做项目时è¯äh³¨æ„POI的版本ã€?br />
    另外需要注意的是HSSF也有它的对xlsåŸÞZºŽäº‹äšg的解析。可以参考例½E‹ä¸­çš„EventExample.java。它通过实现HSSFListener完成从普通流认知Xls中包含的内容åQŒåœ¨apache Cocoon中的org.apache.cocoon.serialization.HSSFSerializer中用åˆîCº†˜q™ä¸ªè§£æžã€‚因为Cocoon2是基于事件的åQŒæ‰€ä»¥POIä¸ÞZº†æä¾›å¿«é€Ÿçš„解析也提供了相应的事件。当然我们自å·×ƒ¹Ÿå¯ä»¥å®žçް˜q™ä¸ªäº‹äšg接口ã€?br />
    因䨓POI˜q˜ä¸æ˜¯ä¸€ä¸ªèƒö够成熟的™å¹ç›®åQŒæ‰€ä»¥æœ‰å¿…要做进一步的开发和‹¹‹è¯•。但是它已经为我们用¾U¯java操作ole2对象提供了可能,而且克服了oleå¯¹è±¡è°ƒç”¨çš„ç¼ºé™øP¼Œæä¾›äº†æœåŠ¡å™¨ç«¯çš„Excel解决æ–ÒŽ¡ˆã€?br />

     



    ]]>
    Excelçš„java处理方式http://www.aygfsteel.com/brock/archive/2006/07/13/57961.htmlbrockbrockThu, 13 Jul 2006 05:48:00 GMThttp://www.aygfsteel.com/brock/archive/2006/07/13/57961.htmlhttp://www.aygfsteel.com/brock/comments/57961.htmlhttp://www.aygfsteel.com/brock/archive/2006/07/13/57961.html#Feedback0http://www.aygfsteel.com/brock/comments/commentRss/57961.htmlhttp://www.aygfsteel.com/brock/services/trackbacks/57961.html Poi即poor object interface之意åQŒæ˜¯poi™å¹ç›®¾l„对微èÊYž®é—­çš„officeæ–‡äšg格式åQˆæŽ¥å£ï¼‰çš„称谓!
    其中提供了对wordå’Œexcelçš„java接口åQŒç”¨æ³•非常简单,òq¶ä¸”是完全免费的åQŒå¯¹ä¸­æ–‡çš„æ”¯æŒä¹Ÿç›¸å½“不错åQŒä¸‹é¢æ˜¯å¤„理excel一个简单的实例åQ?


    package test;

    import java.io.*;
    import org.apache.poi.hssf.usermodel.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;

    public class Test {
    public static void main(String[] args) {
    try {
    /**************创徏一个xls文档*************/
    HSSFWorkbook wb = new HSSFWorkbook();
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    HSSFSheet sheet = wb.createSheet("new sheet");
    HSSFRow row = sheet.createRow((short)0);
    HSSFCell cell = row.createCell((short)0);
    row.createCell((short)1);
    row.createCell((short)2);
    row.createCell((short)3);
    row.createCell((short)4);
    row.createCell((short)5);
    cell.setCellValue("test_write!");
    wb.write(fileOut);
    fileOut.close();
    /*************è¯Õd–òq¶ä¿®æ”¹xls文档***************/
    POIFSFileSystem pfs=new POIFSFileSystem(new FileInputStream("workbook.xls"));
    HSSFWorkbook hwb=new HSSFWorkbook(pfs);
    HSSFSheet hs=hwb.getSheetAt(0);
    HSSFRow hr=hs.getRow(0);
    HSSFCellStyle style=hwb.createCellStyle();
    style.setAlignment(style.ALIGN_CENTER);
    HSSFFont hf=hwb.createFont();
    hf.setFontName("楷体_GB2312");
    style.setFont(hf);
    HSSFCell cl=hr.getCell((short)2);
    cl.setEncoding(cl.ENCODING_UTF_16);
    cl.setCellStyle(style);
    cl.setCellValue("test_modify! ‹¹‹è¯•\u2014\u2014¾~–辑åQ?);
    FileOutputStream fos=new FileOutputStream("workbook.xls");
    hwb.write(fos);
    fos.flush();
    fos.close();
    }
    catch (Exception ex) {
    ex.printStackTrace();
    }
    }
    }



    ]]>
    Ö÷Õ¾Ö©Öë³ØÄ£°å£º Á¬ÖÝÊÐ| ¸ÓÖÝÊÐ| ÔÀÆÕºþÏØ| Î¢É½ÏØ| ̨¶«ÏØ| ¶ÁÊé| ÍôÇåÏØ| ÎÞ¼«ÏØ| ÏØ¼¶ÊÐ| ÄþÉÂÏØ| Öî³ÇÊÐ| ÁÙ¸ßÏØ| ÈýÃÅÏ¿ÊÐ| ½¨Ê¼ÏØ| °ºÈÊÏØ| ÖØÇìÊÐ| ̨½­ÏØ| Ñ®ÑôÏØ| ¯»ôÏØ| µ±ÑôÊÐ| ³çÃ÷ÏØ| ÎÚ³ľÆëÏØ| ¸ßÑôÏØ| ɽµ¤ÏØ| ÕþºÍÏØ| ÍÁÄ¬ÌØ×óÆì| Õê·áÏØ| ¿âÂׯì| Î÷°²ÊÐ| ÕØÖÝÏØ| ¹ÛÌÁÇø| ÄϾ©ÊÐ| ´íÄÇÏØ| ¶Ø»¯ÊÐ| º£¿ÚÊÐ| ÉÂÎ÷Ê¡| ³ÐµÂÏØ| ¿Ë¶«ÏØ| Ë«ÅÆÏØ| ´óÒØÏØ| ³¤º£ÏØ|