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

    在我们实际的开发中,表现层的解决方案虽然有多样,但是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. }  

 

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache poi 导出excel时合并单元格可以使用setRegionStyle方法来设置合并单元格的样式。这个方法接受三个参数,分别是Sheet对象、CellRangeAddress对象和CellStyle对象。在这个方法中,通过循环遍历合并单元格的每一行和每一列,然后获取对应的单元格并设置样式。具体的代码实现可以参考引用\[1\]中的示例代码。 此外,还可以使用PoiModel类来定义导出excel时的数据模型。这个类包含了内容、上一行同一位置内容、行标、列标等属性。可以根据实际需求来使用这个类。具体的代码实现可以参考引用\[2\]和引用\[3\]中的示例代码。 总结起来,Apache poi 导出excel时合并单元格的步骤包括设置合并单元格的样式和定义导出数据的模型。可以根据具体的需求来使用相应的方法和类来实现导出功能。 #### 引用[.reference_title] - *1* *3* [poi 导出Excel 动态 合并单元格](https://blog.csdn.net/weixin_65436454/article/details/127806178)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [使用POI 导出Excel 动态合并单元格](https://blog.csdn.net/weixin_41722928/article/details/112849624)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值