利用POI在Excel文档任意单元格写入数据

来源:互联网 发布:淘宝网民族风女装春装 编辑:程序博客网 时间:2024/05/20 07:35

 在我们实际的开发中,表现层的解决方案虽然有多样,但是IE浏览器已成为最多人使用的浏览器,因为大家都用Windows。在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统、银行系统)。或者是:我们已经习惯用Excel打印。

    Apache的Jakata项目的POI子项目,目前比较成熟的是HSSF接口,处理MSExcel对象。它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。

首先,理解一下一个Excel的文件的组织形式,一个Excel文件对应于一个workbook(HSSFWorkbook),一个workbook可以有多个sheetHSSFSheet)组成,一个sheet是由多个rowHSSFRow)组成,一个row是由多个cellHSSFCell)组成。

    那么,如何利用POI在Excel文档任意单元格写入数据?最近做了个项目,一个人研究了下,现在把代码拿出来和大家分享下!不足之处请前辈们多多指教!

 

Reportbuilder 代码  收藏代码
  1. import java.awt.image.BufferedImage;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import javax.imageio.ImageIO;  
  9. import javax.imageio.stream.ImageInputStream;  
  10.   
  11. import org.apache.poi.hssf.record.PageBreakRecord.Break;  
  12. import org.apache.poi.hssf.usermodel.HSSFCell;  
  13. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;  
  14. import org.apache.poi.hssf.usermodel.HSSFPatriarch;  
  15. import org.apache.poi.hssf.usermodel.HSSFRow;  
  16. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  17. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  18. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
  19.   
  20. public class ReportBuilder   
  21. {  
  22.     public static String outFile_Erro = "Load Template Erro,文件加载失败!!";  
  23.       
  24.     FileOutputStream  fileOutputStream  =  null;  
  25.       
  26.     HSSFWorkbook workbook = null;  
  27.     HSSFSheet   sheet = null;  
  28.   
  29.     HSSFPatriarch  patriarch  =  null;  
  30.       
  31.     /**  
  32.      * @用途:加载一个已经存在的模板,将生成的内容保存到 workbook中  
  33.      * @参数:String templateFile:指索要加载的模板的路径,如:"C:/Tamplates/texting-1.xls"  
  34.      * @用法:templateFile:  String  templateFile_Name1 = "C:/Tamplates/texting-1.xls"           
  35.      * @author Yangcl  
  36.      */   
  37.     public  void loadTemplate(String templateURL)  
  38.     {  
  39.         // TODO Auto-generated method stub  
  40.         boolean a = templateURL.trim().indexOf(".xls") == -1;  
  41.         boolean b = templateURL.trim().indexOf(".XLS") == -1;  
  42. //      boolean c = templateURL.trim().indexOf(".xlsx") == -1;  
  43. //      boolean d = templateURL.trim().indexOf(".XLSX") == -1;  
  44.         if(templateURL == null  || templateURL.trim().equals("") )  
  45.         {  
  46.             //文件不能为空提示  
  47.             System.out.println("文件不能为空提示");  
  48.         }  
  49.         else if(a&&b)// && c&&d)  
  50.         {  
  51.             System.out.println("文件格式不正确!");  
  52.               
  53.         }  
  54.         else{  
  55.             try{  
  56.                 FileInputStream templateFile_Input = new FileInputStream(templateURL);            
  57.                 POIFSFileSystem fs = new POIFSFileSystem(templateFile_Input);  
  58.                   
  59.                 workbook = new  HSSFWorkbook(fs);  
  60.                 sheet =  workbook.getSheetAt(0);  
  61.                   
  62.                 System.out.println("========"+templateURL+"文件加载已完成========");  
  63.             }catch(Exception e){  
  64.                 System.err.println(outFile_Erro);  
  65.             }     
  66.         }  
  67.                    
  68.     }  
  69.       
  70.     /**  
  71.      * 写入非图片格式信息  
  72.      * @描述:这是一个实体类,提供了相应的接口,用于操作Excel,在任意坐标处写入数据。  
  73.      * @参数:String newContent:你要输入的内容  
  74.      *               int beginRow :行坐标,Excel从 0 算起  
  75.      *               int beginCol   :列坐标,Excel从 0 算起  
  76.      * @author Yangcl  
  77.      */  
  78.     public void writeInTemplate( String newContent, int beginRow, int beginCell)  
  79.     {     
  80.         HSSFRow  row  = sheet.getRow(beginRow);   
  81.         if(null == row ){  
  82.             //如果不做空判断,你必须让你的模板文件画好边框,beginRow和beginCell必须在边框最大值以内  
  83.             //否则会出现空指针异常  
  84.             row = sheet.createRow(beginRow);  
  85.         }  
  86.         HSSFCell   cell   = row.getCell(beginCell);  
  87.         if(null == cell){  
  88.             cell = row.createCell(beginCell);  
  89.         }  
  90.         //设置存入内容为字符串  
  91.         cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
  92.         //向单元格中放入值  
  93.         cell.setCellValue(newContent);      
  94.     }  
  95.       
  96.       
  97.     /**  
  98.      * 写入图片格式信息  
  99.      * @描述:这是一个实体类,提供了相应的接口,用于操作Excel,在任意坐标处写入数据。  
  100.      * @参数:  
  101.      *               String  imageFileURL:他接受一个外界传入的图片路径,图片以  *.jpeg 形式存在。  
  102.      *   
  103.      * @用法:  
  104.      *               ReportBuilder twi = new ReportBuilder();  
  105.      *               String imageFileURL = "D:/workspace/Tamplates/1.jpeg";   
  106.      *               twi.writeInTemplate(imageFileURL , 0,000, (short)65, (short)88);  
  107.      *   
  108.      * @param dx1 :第一个cell开始的X坐标  
  109.      * @param dy1 :第一个cell开始的Y坐标  
  110.      * @param dx2 :第二个cell开始的X坐标  
  111.      * @param dy2 :第二个cell开始的Y坐标  
  112.      * @param col1   :图片的左上角放在第几个列cell (the column(o based); of the first cell)  
  113.      * @param row1  :图片的左上角放在第几个行cell (the row(o based); of the first cell)  
  114.      * @param col2   :图片的右下角放在第几个列cell (the column(o based); of the second cell)  
  115.      * @param row2  :图片的右下角放在第几个行cell (the row(o based); of the second cell)  
  116.      *   
  117.      * @author Yangcl  
  118.      */  
  119.     public  void writeInTemplate(String  imageFileURL , int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2  )  
  120.     {     
  121.         BufferedImage  bufferImage = null;  
  122.           
  123.         //写入图片格式信息  
  124.         try  
  125.         {             
  126.             ByteArrayOutputStream     byteArrayOutputStream = new ByteArrayOutputStream();  
  127.               
  128.             //先把读入的图片放到第一个 ByteArrayOutputStream 中,用于产生ByteArray     
  129.             File fileImage = new File(imageFileURL);      
  130.               
  131.             bufferImage = ImageIO.read(fileImage);        
  132.             ImageIO.write(bufferImage, "JPG", byteArrayOutputStream);  
  133.             System.out.println("ImageIO 写入完成");  
  134.               
  135.             //准备插入图片  
  136.             HSSFPatriarch  patriarch  =  sheet.createDrawingPatriarch();  
  137.             HSSFClientAnchor  anchor  =   new  HSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);      
  138.               
  139.             //插入图片    
  140.             byte[] pictureData = byteArrayOutputStream.toByteArray();  
  141.             int pictureFormat   = HSSFWorkbook.PICTURE_TYPE_JPEG;  
  142.             int pictureIndex = workbook.addPicture(pictureData, pictureFormat);  
  143.             patriarch.createPicture(anchor, pictureIndex);  
  144.               
  145.         }catch(Exception e){  
  146.             e.printStackTrace();  
  147.             System.out.println("IO Erro:" + e.getMessage());  
  148.         }finally  
  149.         {  
  150.             if(fileOutputStream != null)  
  151.             {  
  152.                 try{  
  153.                     fileOutputStream.close();  
  154.                 }catch(IOException io){  
  155.                     io.printStackTrace();  
  156.                 }  
  157.             }  
  158.         }  
  159.     }  
  160.       
  161.     /**  
  162.      * 写入图片格式信息  
  163.      * @描述:这是一个实体类,提供了相应的接口,用于操作Excel,在任意坐标处写入数据。  
  164.      * @参数:  
  165.      *               ImageInputStream imageInputStream:他接受一个外界传入的图片流,图片以流形式存在。  
  166.      *   
  167.      * @用法:  
  168.      *   
  169.      *   
  170.      *   
  171.      *   
  172.      * @param dx1 :第一个cell开始的X坐标  
  173.      * @param dy1 :第一个cell开始的Y坐标  
  174.      * @param dx2 :第二个cell开始的X坐标  
  175.      * @param dy2 :第二个cell开始的Y坐标  
  176.      * @param col1   :图片的左上角放在第几个列cell (the column(o based); of the first cell)  
  177.      * @param row1  :图片的左上角放在第几个行cell (the row(o based); of the first cell)  
  178.      * @param col2   :图片的右下角放在第几个列cell (the column(o based); of the second cell)  
  179.      * @param row2  :图片的右下角放在第几个行cell (the row(o based); of the second cell)  
  180.      *   
  181.      * @author Yangcl  
  182.      */  
  183.     public  void writeInTemplate(ImageInputStream imageInputStream , int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2  )  
  184.     {  
  185.         BufferedImage  bufferImage = null;        
  186.         //写入图片格式信息  
  187.         try  
  188.         {             
  189.             ByteArrayOutputStream     byteArrayOutputStream = new ByteArrayOutputStream();        
  190.             //先把读入的图片放到一个 ByteArrayOutputStream 中,用于产生ByteArray           
  191.             bufferImage = ImageIO.read(imageInputStream);         
  192.             ImageIO.write(bufferImage, "JPG", byteArrayOutputStream);  
  193.             System.out.println("ImageIO 写入完成");  
  194.               
  195.             //准备插入图片  
  196.             HSSFPatriarch  patriarch  =  sheet.createDrawingPatriarch();  
  197.             HSSFClientAnchor  anchor  =   new  HSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);      
  198.               
  199.             //插入图片    
  200.             byte[] pictureData = byteArrayOutputStream.toByteArray();  
  201.             int pictureFormat   = HSSFWorkbook.PICTURE_TYPE_JPEG;  
  202.             int pictureIndex = workbook.addPicture(pictureData, pictureFormat);  
  203.             patriarch.createPicture(anchor, pictureIndex);  
  204.         }catch(Exception e){  
  205.             e.printStackTrace();  
  206.             System.out.println("IO Erro:" + e.getMessage());  
  207.         }finally  
  208.         {  
  209.             if(fileOutputStream != null)  
  210.             {  
  211.                 try{  
  212.                     fileOutputStream.close();  
  213.                 }catch(IOException io){  
  214.                     io.printStackTrace();  
  215.                 }  
  216.             }  
  217.         }  
  218.     }  
  219.     /**  
  220.      * 保存模板  
  221.      * @描述:这个方法用于保存workbook(工作薄)中的内容,并写入到一个Excel文件中  
  222.      * @参数:String templateFile:取得已经保存的类模板 路径名称  
  223.      * @用法:templateFile:String  templateFile_Name1 = "C:/Tamplates/texting-1.xls"  
  224.      *                TemplateAdapter ta  = new TemplateAdapter();  
  225.      *                ta.SaveTemplate(templateFile_Name1);  
  226.      * @param templateFile  
  227.      */  
  228.     public void SaveTemplate(String templateFile)  
  229.     {  
  230.         try{  
  231.               
  232.             //建立输出流  
  233.             fileOutputStream = new FileOutputStream(templateFile);  
  234.             workbook.write(fileOutputStream);  
  235.           
  236.         }catch(Exception e){  
  237.             e.printStackTrace();  
  238.             System.out.println("IO Erro" + e.getMessage());  
  239.         }finally  
  240.         {  
  241.             if(fileOutputStream != null)  
  242.             {  
  243.                 try{  
  244.                     fileOutputStream.close();  
  245.                 }catch(IOException io){  
  246.                     io.printStackTrace();  
  247.                 }  
  248.             }  
  249.         }  
  250.     }  
  251.   
  252.       
  253. }  

 

        这段代码是完整的。我开始找了很久关于如何利用POI在Excel文档任意单元格写入数据的文章,从而实现一个以面向服务为目标的报表系统,但很遗憾,在国内的网站上没有找到。而且介绍的比较基础,对于急需使用POI,但又没有时间仔细研究的人来说,难过急了。上面的代码有比较详细的注释,相信大家看的懂。如果您要转载这篇文章,请注明出处。开源万岁~祝您成功。文档依赖的两个 jar包:commons-codec-1.5.jar和poi-3.8-20120326.jar见附件。这字体真让人蛋疼菊紧!

 

 

 

 更多信息请浏览:http://www.open-open.com/home/space-135360-do-blog-id-9614.html

0 0
原创粉丝点击