Java 导出Excel

    导出Excel 有多种方式,这里就先介绍  Jakarta POI 这一种。主要靠的是一个Jar 包 poi-3.7.jar 本次代码中所用就是该版本的包,其他版本应该差别不大。
    在上代码之前,感觉有必需认识一下这Excel 这个东西,看Java 中是怎么对象化的。
Java 导出Excel_第1张图片
    像上面这一个个.xls 结尾的一个个Excel 文档可以是一个对象,在poi 中叫 HSSFWorkbook 。
    打开一个
Java 导出Excel_第2张图片
    看指示那里,这里可以有很多个工作簿,在poi 中叫 HSSFSheet。
    再看
Java 导出Excel_第3张图片
    这样一行在 poi 中叫 HSSFRow  ,每行中一个一个的单元格 叫 HSSFCell ,到此基本的元素介绍得差不多。
    通过上面的介绍,我们可以很清楚的知道,每个HSSFWorkbook 中有很多个 HSSFSheet ,而每个 HSSFSheet 中也有很多个HSSFRow,每个 HSSFRow   中也有很多的HSSFCell 。它们是这样一层一层地包下去,在想存在下层必需得存在上层。
好,那么我们上代码:
HSSFWorkbook   wb   =   new   HSSFWorkbook(); //创建excel的文档对象
HSSFSheet   sheet   =   wb .createSheet(); //创建excel的表单
HSSFRow   row0   =   sheet .createRow(( short )0); // 创建 excel的行
HSSFCell   cell0   =   row0 .createCell(0); // 创建 excel的格子单元  
cell0 .setCellValue( "测试表头" );//格子内放置的内容
sheet .addMergedRegion( new   CellRangeAddress(0, 0, 0, 3));//格子所占的位置
    以下是上面代码所产生的效果:
Java 导出Excel_第4张图片
    前5 行代码相信不用我解释了吧。那么我们来说说最后一行是怎么回事。最后一行是设置这个表单工作簿中某些格子占位情况的。里面主要有4个参数,从左到右分别是:开始行位置(从0开始,比如就是0),结束行位置(与开始行相同说明只占一行,比如也是0,1就代表占了0、1这两行),开始列位置(与行的情况一样),结束列位置(与行的情况一样)。
    那上例子上面的参数说明的事情就是,将第一行,从0开始到第3列合并在一起,让别人看起来像一个格子。再看效果图果然是这样子。
    如果我把上图效果改一下,改成下面这样:
Java 导出Excel_第5张图片
    相信大家也很快把其他位置的占位参数设置出来:位置2 明显是占了两行一列,那参数应该是0, 1,4,4.位置3就原始的一格1,1,0,0。位置4也像3一样 1,1,2,2.
    大概的设置说完了,到这里大家应该知道如何做导出Excel 了,因为基本的要素都说完了。所谓的很复杂的表都是由一个个格子组成的,我们一个一个地像上面那样画出来后,组成的就是复杂的表了。
    下面上个表头的代码
HSSFWorkbook   wb   =   new   HSSFWorkbook(); //创建excel的文档对象
HSSFSheet   sheet   =   wb .createSheet(); //创建excel的表单
HSSFRow   row0   =   sheet .createRow(( short )0); // 创建 excel的行
HSSFCell   cell0   =   row0 .createCell(0); // 创建 excel的格子单元  
cell0 .setCellValue( "测试表头" );//格子内放置的内容
sheet .addMergedRegion( new   CellRangeAddress(0, 0, 0, 3));//格子所占的位置

     HSSFRow   row1   =   sheet .createRow(1);
        HSSFCell   cell1_0   =   row1 .createCell(0);       
          cell1_0 .setCellValue( "序号" );
      sheet .addMergedRegion( new   CellRangeAddress(1, 2, 0, 0));
     
        HSSFCell   cell1_1   =   row1 .createCell(1);       
          cell1_1 .setCellValue( "姓名" );
          sheet .addMergedRegion( new   CellRangeAddress(1, 2, 1, 1));
       
        HSSFCell   cell1_2   =   row1 .createCell(2);       
          cell1_2 .setCellValue( "身份信息" );
          sheet .addMergedRegion( new   CellRangeAddress(1, 1, 2, 3));
       
        HSSFRow   row2   =   sheet .createRow(2);
        HSSFCell   cell2_2   =   row2 .createCell(2);       
          cell2_2 .setCellValue( "性别" );
      sheet .addMergedRegion( new   CellRangeAddress(2, 2, 2, 2));
     
        HSSFCell   cell2_3   =   row2 .createCell(3);       
          cell2_3 .setCellValue( "出生年月" );
          sheet .addMergedRegion( new   CellRangeAddress(2, 2, 3, 3));
    效果如下面
Java 导出Excel_第6张图片

    然后列表中的信息也是如法炮制弄上去就可以了。到这里,只是简单的会把东西弄上去了。但是还没完,这样的表单太丑了,poi 还提供了样式的对象
它叫 HSSFCellStyle 它里面还有个设置文字相关的字体对象 叫 HSSFFont
    下面上完整代码:
public   class   ExportExcel {
      public   static   void   main(String[]   args ) {
           HSSFWorkbook   wb   =   new   HSSFWorkbook(); //创建excel的文档对象
           HSSFSheet   sheet   =   wb .createSheet(); //创建excel的表单
            //设置工作表名称
           wb .setSheetName(0,   "测试表头" ); //表单名称
           
      //设置样式
        HSSFCellStyle   sheetTitleStyle   =   wb .createCellStyle(); //cell样式
           HSSFFont   font   =   wb .createFont(); //excel字体
            font .setFontName( "宋体" );   // 字体
            font .setFontHeightInPoints(( short )14);   // 字体高度
            font .setBoldweight(HSSFFont. BOLDWEIGHT_BOLD );   // 宽度
           
            sheetTitleStyle .setFont( font );
           sheetTitleStyle .setAlignment(HSSFCellStyle. ALIGN_CENTER ); //横向居中
           sheetTitleStyle .setVerticalAlignment(HSSFCellStyle. VERTICAL_CENTER );   // 纵向居中
     
            int   b   = 3;
      //设置列宽度
      sheet .setColumnWidth(0, 838* b );
      sheet .setColumnWidth(1, 838* b );
      sheet .setColumnWidth(2, 838* b );
      sheet .setColumnWidth(3, 838* b );
           
           HSSFRow   row0   =   sheet .createRow(( short )0); //excel的行
          row0 .setHeightInPoints(40);
        HSSFCell   cell0   =   row0 .createCell(0); //excel的格子单元
      cell0 .setCellStyle( sheetTitleStyle );       
      cell0 .setCellValue( "测试表头" );
      sheet .addMergedRegion( new   CellRangeAddress(0, 0, 0, 3));
     
     
     HSSFRow   row1   =   sheet .createRow(1);
          //设置行高
          row1 .setHeight(( short ) 800);
        HSSFCell   cell1_0   =   row1 .createCell(0);
          cell1_0 .setCellStyle( sheetTitleStyle );       
          cell1_0 .setCellValue( "序号" );
      sheet .addMergedRegion( new   CellRangeAddress(1, 2, 0, 0));
     
        HSSFCell   cell1_1   =   row1 .createCell(1);
          cell1_1 .setCellStyle( sheetTitleStyle );       
          cell1_1 .setCellValue( "姓名" );
          sheet .addMergedRegion( new   CellRangeAddress(1, 2, 1, 1));
       
        HSSFCell   cell1_2   =   row1 .createCell(2);
          cell1_2 .setCellStyle( sheetTitleStyle );       
          cell1_2 .setCellValue( "身份信息" );
          sheet .addMergedRegion( new   CellRangeAddress(1, 1, 2, 3));
       
        HSSFRow   row2   =   sheet .createRow(2);
          //设置行高
         row2 .setHeight(( short ) 800);
        HSSFCell   cell2_2   =   row2 .createCell(2);
          cell2_2 .setCellStyle( sheetTitleStyle );       
          cell2_2 .setCellValue( "性别" );
      sheet .addMergedRegion( new   CellRangeAddress(2, 2, 2, 2));
     
        HSSFCell   cell2_3   =   row2 .createCell(3);
          cell2_3 .setCellStyle( sheetTitleStyle );       
          cell2_3 .setCellValue( "出生年月" );
          sheet .addMergedRegion( new   CellRangeAddress(2, 2, 3, 3));
       
        HSSFRow   row3   =   sheet .createRow(3);
          //设置行高
          row3 .setHeight(( short ) 800);
        HSSFCell   cell3_0   =   row3 .createCell(0);
          cell3_0 .setCellStyle( sheetTitleStyle );       
          cell3_0 .setCellValue( "1" );
          sheet .addMergedRegion( new   CellRangeAddress(3, 3, 0, 0));
       
        HSSFCell   cell3_1   =   row3 .createCell(1);
          cell3_1 .setCellStyle( sheetTitleStyle );       
          cell3_1 .setCellValue( "小明" );
          sheet .addMergedRegion( new   CellRangeAddress(3, 3, 1, 1));
        HSSFCell   cell3_2   =   row3 .createCell(2);
          cell3_2 .setCellStyle( sheetTitleStyle );       
          cell3_2 .setCellValue( "男" );
          sheet .addMergedRegion( new   CellRangeAddress(3, 3, 2, 2));
        HSSFCell   cell3_3   =   row3 .createCell(3);
          cell3_3 .setCellStyle( sheetTitleStyle );       
          cell3_3 .setCellValue( "201801" );
          sheet .addMergedRegion( new   CellRangeAddress(3, 3, 3, 3));
       
                
           FileOutputStream   output   =   null ;
            try   {
                 output   =   new   FileOutputStream( "E:\\workspace\\测试Excel.xls" );
           }   catch   (FileNotFoundException   e ) {
                 //   TODO   Auto-generated catch block
                 e .printStackTrace();
           }
            try   {
                 wb .write( output );
           }   catch   (IOException   e ) {
                 //   TODO   Auto-generated catch block
                 e .printStackTrace();
           } 
            try   {
                 output .flush();
                 output .close();
           }   catch   (IOException   e ) {
                 //   TODO   Auto-generated catch block
                 e .printStackTrace();
           }    finally {
                
           }
           
     }
}

    效果如下:
    当然我这里只是简单设置了几个样式,还有很多可以设置的,自己查下API 就可以自由设置了。在些就不多说了。
Java 导出Excel_第7张图片
后附:如果工作时写的代码也像上面那样,是要挨骂的。作为程序员应该痛恨写重复的代码,下面为大家付上整理版(当然下面的代码还有很多可以改进的地方,比如把方法做得更灵活,让更多可以以活动设置的东西作为参数传进来就可以了):
package com.hlm.java.excel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
public class ExportExcel {
      public static void main(String[] args ) {
           HSSFWorkbook  wb = new HSSFWorkbook(); //创建excel的文档对象
           HSSFSheet  sheet = wb .createSheet(); //创建excel的表单
            //设置工作表名称
         wb .setSheetName(0, "测试表头" ); //表单名称
           
         HSSFCellStyle  sheetStyle getStyle ( wb );
     
            int b = 3;
      //设置列宽度
      sheet .setColumnWidth(0, 838* b );
      sheet .setColumnWidth(1, 838* b );
      sheet .setColumnWidth(2, 838* b );
      sheet .setColumnWidth(3, 838* b );
           
           HSSFRow  row0 = sheet .createRow(( short )0); //excel的行
        row0 .setHeightInPoints(40);
        buildCell ( sheet , row0 , sheetStyle , "测试表头" ,0,0,0,3,0);
           
     HSSFRow  row1 = sheet .createRow(1);
        //设置行高
        row1 .setHeight(( short ) 800);
       
      buildCell ( sheet , row1 , sheetStyle , "序号" ,1,2,0,0,0);
      buildCell ( sheet , row1 , sheetStyle , "姓名" ,1,2,1,1,1);
      buildCell ( sheet , row1 , sheetStyle , "身份信息" ,1,1,2,3,2);
                             
        HSSFRow  row2 = sheet .createRow(2);
        //设置行高
        row2 .setHeight(( short ) 800);
        buildCell ( sheet , row2 , sheetStyle , "性别" ,2,2,2,2,2);
        buildCell ( sheet , row2 , sheetStyle , "出生年月" ,2,2,3,3,3);
       
        HSSFRow  row3 = sheet .createRow(3);
        //设置行高
        row3 .setHeight(( short ) 800);
        buildCell ( sheet , row3 , sheetStyle , "1" ,3,3,0,0,0);
        buildCell ( sheet , row3 , sheetStyle , "小明" ,3,3,1,1,1);
        buildCell ( sheet , row3 , sheetStyle , "男" ,3,3,2,2,2);
        buildCell ( sheet , row3 , sheetStyle , "201801" ,3,3,3,3,3);
               
        writeOutPutStream ( wb , "E:\\workspace\\测试Excel.xls" );           
           
                     
     }
      /**
      * 获取样式:“宋体”、14号、居中显示
      * @param wb
      * @return
      */
      private static HSSFCellStyle getStyle(HSSFWorkbook wb ){
            //设置样式
        HSSFCellStyle  sheetStyle = wb .createCellStyle(); //cell样式
           HSSFFont  font = wb .createFont(); //excel字体
            font .setFontName( "宋体" ); // 字体
            font .setFontHeightInPoints(( short )14); // 字体高度
            font .setBoldweight(HSSFFont. BOLDWEIGHT_BOLD ); // 宽度
           
            sheetStyle .setFont( font );
           sheetStyle .setAlignment(HSSFCellStyle. ALIGN_CENTER ); //横向居中
           sheetStyle .setVerticalAlignment(HSSFCellStyle. VERTICAL_CENTER ); // 纵向居中
            return  sheetStyle ;
     }
      /**
      * 构建单元格
      * @param sheet 工作簿对象
      * @param row 行对象
      * @param style 样式对象
      * @param value 单元格中值
      * @param firstRow 单元格占起始行
      * @param lastRow 单元格占结束行
      * @param firstCol 单元格占起始列
      * @param lastCol 单元格占结束列
      * @param cellIdex 该行的第几个单元格(多行合并的取首个)
      */
   private static void buildCell(HSSFSheet sheet , HSSFRow row , HSSFCellStyle  style , String value
                                             , int  firstRow , int  lastRow , int  firstCol , int  lastCol , int  cellIdex ){
         HSSFCell cell = row .createCell( cellIdex );
         cell .setCellStyle( style );        
         cell .setCellValue( value );
        sheet .addMergedRegion( new CellRangeAddress( firstRow , lastRow , firstCol , lastCol ));
   }
    /**
      * 获取输出流并将Excel 导出
      * @param wb
      * @param dirAndFilesName
      * @return
      */
      private  static FileOutputStream writeOutPutStream(HSSFWorkbook wb ,String  dirAndFilesName ){
           FileOutputStream  output = null ;
            try {
                 output = new FileOutputStream( dirAndFilesName );
           } catch (FileNotFoundException e ) {
                 // TODO Auto-generated catch block
                 e .printStackTrace();
           }
            try {
                 wb .write( output );
           } catch (IOException e ) {
                 // TODO Auto-generated catch block
                 e .printStackTrace();
           } 
            try {
                 output .flush();
                 output .close();
           } catch (IOException e ) {
                 // TODO Auto-generated catch block
                 e .printStackTrace();
           }
            return  output ;
     }
}

你可能感兴趣的:(Java)