java操作excel表格。

虽说java直接读取excel不是很常用,但是小日本可是非常重视excel的使用,在项目中,远远比word使用的要广泛了 ,说不定那天就让你读取或者存取成excel格式的文档,现在就来个入门教程吧。到真正需要时,只要去查看相应的API文档就可以了。

从头说起,java读取excel的方式常见的有两种:


一种是Java-To-Com的方式:

(1)   jCom   (2)   Jacob

该方法是利用Java-Com桥的方式来读写Excel文件,需要后台有Com组件的支持,不能脱离Windows平台使用,有违java的跨平台的宗旨,故不推荐使用这种方法。

另一种是直接对Excel文件进行操作:

(3)   jExcel   (4)   POI

这种方法是直接使用纯Java API存取Excel文件,可以直接从磁盘文件或者Java的输入输出流中读写Excel文件。不必依赖于Windows平台以及Com组件,使用起来很方便。

jExcel与POI都是开源的Java项目,jExcel是sourceforge的开源项目(http://jexcelapi.sourceforge.net/), jExcel最近的版本是2.6.5 的2007年8月出的

POI是Apache的开源项目(http://jakarta.apache.org/poi/  POI的最近版本是POI3.0.1final 版。

我这里就使用了POI,jExcel还没用呢,使用方法很简单,并且POI是一个系列包,其中还有对word,ppt等文件操作,感觉很方便,下面给两个入门的例子:

 

public   class  WriterExcel  {

    
/**
     * 
@param args
     
*/

    @SuppressWarnings(
"deprecation")
    
public static void main(String[] args) {

        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 value in it.
        HSSFCell cell1 = row.createCell((short)0);
        cell1.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);
        
/**
         * Creating Date Cells
         
*/

        
// Create a cell and put a date value in it.  The first cell is not styled
        
// as a date.
        row.createCell((short)4).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"));
        cell1 
= row.createCell((short)5);
        cell1.setCellValue(
new Date());
        cell1.setCellStyle(cellStyle);
        
        
/**
         * Demonstrates various alignment options
         
*/

            row 
= sheet.createRow((short)6 );
            createCell(wb, row, (
short0, HSSFCellStyle.ALIGN_CENTER);
            createCell(wb, row, (
short1, HSSFCellStyle.ALIGN_CENTER_SELECTION);
            createCell(wb, row, (
short2, HSSFCellStyle.ALIGN_FILL);
            createCell(wb, row, (
short3, HSSFCellStyle.ALIGN_GENERAL);
            createCell(wb, row, (
short4, HSSFCellStyle.ALIGN_JUSTIFY);
            createCell(wb, row, (
short5, HSSFCellStyle.ALIGN_LEFT);
            createCell(wb, row, (
short6, HSSFCellStyle.ALIGN_RIGHT);
        
/**
         * create a 9*9 table
         
*/

        
//method one
        sheet = wb.createSheet("9-9 v1");
        
for(short y=8;0<=y;y--){
            row 
= sheet.createRow(y);
            
for(short x=(short) (8-y);x<9;){
                HSSFCell cell 
= row.createCell(x);
                x
++;
                cell.setCellValue((
9-y)+"*"+x+"="+(9-y)*x);
            }

        }

        
//method 2
        HSSFSheet sheet2 = wb.createSheet("9-9 v2");
        
for(short y=0;y<9;y++){
            row 
= sheet2.createRow(y);
            
for(short x=(short)(8-y);x<9;){
                HSSFCell cell 
= row.createCell(x);
                x
++;
                cell.setCellValue((
9-y)+"*"+x+"="+(9-y)*x);
            }

        }

        
//      Write the output to a file
        try {
            FileOutputStream fileOut 
= new FileOutputStream("workbook.xls");
            wb.write(fileOut);
            fileOut.close();
            
        }
 catch (FileNotFoundException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }
 catch (IOException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    
/**
     * 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);
    }

}

 

 呵呵,其实这一段代码很简单,在POI的文档里面也有部分,我写了个9*9的乘法表。

下面这个例子思想很好使用了css的思想,试想如果我们把所有常用的文档格式都定义好,以后就可以反复使用了,或者做稍微的修改。

 

short  rownum;

//  create a new file
FileOutputStream  out   =   new  FileOutputStream( " workbook.xls " );
//  create a new workbook
HSSFWorkbook wb  =   new  HSSFWorkbook();
//  create a new sheet
HSSFSheet s  =  wb.createSheet();
//  declare a row object reference
HSSFRow r  =   null ;
//  declare a cell object reference
HSSFCell c  =   null ;
//  create 3 cell styles
HSSFCellStyle cs  =  wb.createCellStyle();
HSSFCellStyle cs2 
=  wb.createCellStyle();
HSSFCellStyle cs3 
=  wb.createCellStyle();
HSSFDataFormat df 
=  wb.createDataFormat();
//  create 2 fonts objects
HSSFFont f  =  wb.createFont();
HSSFFont f2 
=  wb.createFont();

// set font 1 to 12 point type
f.setFontHeightInPoints(( short 12 );
// make it blue
f.setColor( ( short ) 0xc  );
//  make it bold
// arial is the default font
f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

// set font 2 to 10 point type
f2.setFontHeightInPoints(( short 10 );
// make it red
f2.setColor( ( short )HSSFFont.COLOR_RED );
// make it bold
f2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

f2.setStrikeout( 
true  );

// set cell stlye
cs.setFont(f);
// set the cell format 
cs.setDataFormat(df.getFormat( " #,##0.0 " ));

// set a thin border
cs2.setBorderBottom(cs2.BORDER_THIN);
// fill w fg fill color
cs2.setFillPattern(( short ) HSSFCellStyle.SOLID_FOREGROUND);
// set the cell format to text see HSSFDataFormat for a full list
cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat( " text " ));

//  set the font
cs2.setFont(f2);

//  set the sheet name in Unicode
wb.setSheetName( 0 " Тестовая  "   +  
                   
" Страничка "
                HSSFWorkbook.ENCODING_UTF_16 );
//  in case of compressed Unicode
//  wb.setSheetName(0, "HSSF Test", HSSFWorkbook.ENCODING_COMPRESSED_UNICODE );
//  create a sheet with 30 rows (0-29)
for  (rownum  =  ( short 0 ; rownum  <   30 ; rownum ++ )
{
    
// create a row
    r = s.createRow(rownum);
    
// on every other row
    if ((rownum % 2== 0)
    
{
        
// make the row height bigger  (in twips - 1/20 of a point)
        r.setHeight((short0x249);
    }


    
//r.setRowNum(( short ) rownum);
    
// create 10 cells (0-9) (the += 2 becomes apparent later
    for (short cellnum = (short0; cellnum < 10; cellnum += 2)
    
{
        
// create a numeric cell
        c = r.createCell(cellnum);
        
// do some goofy math to demonstrate decimals
        c.setCellValue(rownum * 10000 + cellnum
                
+ (((double) rownum / 1000)
                
+ ((double) cellnum / 10000)));

        String cellValue;

        
// create a string cell (see why += 2 in the
        c = r.createCell((short) (cellnum + 1));
        
        
// on every other row
        if ((rownum % 2== 0)
        
{
            
// set this cell to the first cell style we defined
            c.setCellStyle(cs);
            
// set the cell's string value to "Test"
            c.setEncoding( HSSFCell.ENCODING_COMPRESSED_UNICODE );
            c.setCellValue( 
"Test" );
        }

        
else
        
{
            c.setCellStyle(cs2);
            
// set the cell's string value to "Тест"
            c.setEncoding( HSSFCell.ENCODING_UTF_16 );
            c.setCellValue( 
"Тест" );
        }



        
// make this column a bit wider
        s.setColumnWidth((short) (cellnum + 1), (short) ((50 * 8/ ((double1 / 20)));
    }

}


// draw a thick black border on the row at the bottom using BLANKS
//  advance 2 rows
rownum ++ ;
rownum
++ ;

=  s.createRow(rownum);

//  define the third style to be the default
//  except with a thick black border at the bottom
cs3.setBorderBottom(cs3.BORDER_THICK);

// create 50 cells
for  ( short  cellnum  =  ( short 0 ; cellnum  <   50 ; cellnum ++ )
{
    
//create a blank type cell (no value)
    c = r.createCell(cellnum);
    
// set it to the thick black border style
    c.setCellStyle(cs3);
}


// end draw thick black border


//  demonstrate adding/naming and deleting a sheet
//  create a sheet, set its title then delete it
=  wb.createSheet();
wb.setSheetName(
1 " DeletedSheet " );
wb.removeSheetAt(
1 );
// end deleted sheet

//  write the workbook to the output stream
//  close our file (don't blow out our file handles
wb.write( out );
out .close();

 

这个例子来源于官方文档,但是我们可以对其改造 一下,我们可以定义一个静态类,用来保存常用css类型,一个系统中生成的文档一般都属于同一种风格,这样我们倒是后只需要调用就是了,很省功夫的。

有时间可以研究一下金山的office还有open office,制作一个小软件能够使他们相互转化,也能做批量格式转化,蛮不错的,如果金山有开放的接口供用户扩展,那样的话我们自己可以写一个类似于POI的jar包,供大家使用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值