利用POI在Excel文檔任意單元格寫入數據

    在我們實際的開發中,表現層的解決方案雖然有多樣,但是IE瀏覽器已成爲最多人使用的瀏覽器,因爲大家都用Windows。在企業辦公系統中,常常有客戶這樣子要求:你要把我們的報表直接用Excel打開(電信系統、銀行系統)。或者是:我們已經習慣用Excel打印。

    ApacheJakata項目的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. }  

 

    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章