Apache的Jakata項目的POI子項目,目前比較成熟的是HSSF接口,處理MSExcel對象。它不象我們僅僅是用csv生成的沒有格式的可以由Excel轉換的東西,而是真正的Excel對象,你可以控制一些屬性如sheet,cell等等。
那麼,如何利用POI在Excel文檔任意單元格寫入數據?最近做了個項目,一個人研究了下,現在把代碼拿出來和大家分享下!不足之處請前輩們多多指教!
- import java.awt.image.BufferedImage;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- import javax.imageio.stream.ImageInputStream;
- import org.apache.poi.hssf.record.PageBreakRecord.Break;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
- import org.apache.poi.hssf.usermodel.HSSFPatriarch;
- 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.poifs.filesystem.POIFSFileSystem;
- public class ReportBuilder
- {
- public static String outFile_Erro = "Load Template Erro,文件加載失敗!!";
- FileOutputStream fileOutputStream = null;
- HSSFWorkbook workbook = null;
- HSSFSheet sheet = null;
- HSSFPatriarch patriarch = null;
- /**
- * @用途:加載一個已經存在的模板,將生成的內容保存到 workbook中
- * @參數:String templateFile:指索要加載的模板的路徑,如:"C:/Tamplates/texting-1.xls"
- * @用法:templateFile: String templateFile_Name1 = "C:/Tamplates/texting-1.xls"
- * @author Yangcl
- */
- public void loadTemplate(String templateURL)
- {
- // TODO Auto-generated method stub
- boolean a = templateURL.trim().indexOf(".xls") == -1;
- boolean b = templateURL.trim().indexOf(".XLS") == -1;
- // boolean c = templateURL.trim().indexOf(".xlsx") == -1;
- // boolean d = templateURL.trim().indexOf(".XLSX") == -1;
- if(templateURL == null || templateURL.trim().equals("") )
- {
- //文件不能爲空提示
- System.out.println("文件不能爲空提示");
- }
- else if(a&&b)// && c&&d)
- {
- System.out.println("文件格式不正確!");
- }
- else{
- try{
- FileInputStream templateFile_Input = new FileInputStream(templateURL);
- POIFSFileSystem fs = new POIFSFileSystem(templateFile_Input);
- workbook = new HSSFWorkbook(fs);
- sheet = workbook.getSheetAt(0);
- System.out.println("========"+templateURL+"文件加載已完成========");
- }catch(Exception e){
- System.err.println(outFile_Erro);
- }
- }
- }
- /**
- * 寫入非圖片格式信息
- * @描述:這是一個實體類,提供了相應的接口,用於操作Excel,在任意座標處寫入數據。
- * @參數:String newContent:你要輸入的內容
- * int beginRow :行座標,Excel從 0 算起
- * int beginCol :列座標,Excel從 0 算起
- * @author Yangcl
- */
- public void writeInTemplate( String newContent, int beginRow, int beginCell)
- {
- HSSFRow row = sheet.getRow(beginRow);
- if(null == row ){
- //如果不做空判斷,你必須讓你的模板文件畫好邊框,beginRow和beginCell必須在邊框最大值以內
- //否則會出現空指針異常
- row = sheet.createRow(beginRow);
- }
- HSSFCell cell = row.getCell(beginCell);
- if(null == cell){
- cell = row.createCell(beginCell);
- }
- //設置存入內容爲字符串
- cell.setCellType(HSSFCell.CELL_TYPE_STRING);
- //向單元格中放入值
- cell.setCellValue(newContent);
- }
- /**
- * 寫入圖片格式信息
- * @描述:這是一個實體類,提供了相應的接口,用於操作Excel,在任意座標處寫入數據。
- * @參數:
- * String imageFileURL:他接受一個外界傳入的圖片路徑,圖片以 *.jpeg 形式存在。
- *
- * @用法:
- * ReportBuilder twi = new ReportBuilder();
- * String imageFileURL = "D:/workspace/Tamplates/1.jpeg";
- * twi.writeInTemplate(imageFileURL , 0,0, 0, 0, (short)6, 5, (short)8, 8);
- *
- * @param dx1 :第一個cell開始的X座標
- * @param dy1 :第一個cell開始的Y座標
- * @param dx2 :第二個cell開始的X座標
- * @param dy2 :第二個cell開始的Y座標
- * @param col1 :圖片的左上角放在第幾個列cell (the column(o based); of the first cell)
- * @param row1 :圖片的左上角放在第幾個行cell (the row(o based); of the first cell)
- * @param col2 :圖片的右下角放在第幾個列cell (the column(o based); of the second cell)
- * @param row2 :圖片的右下角放在第幾個行cell (the row(o based); of the second cell)
- *
- * @author Yangcl
- */
- public void writeInTemplate(String imageFileURL , int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2 )
- {
- BufferedImage bufferImage = null;
- //寫入圖片格式信息
- try
- {
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- //先把讀入的圖片放到第一個 ByteArrayOutputStream 中,用於產生ByteArray
- File fileImage = new File(imageFileURL);
- bufferImage = ImageIO.read(fileImage);
- ImageIO.write(bufferImage, "JPG", byteArrayOutputStream);
- System.out.println("ImageIO 寫入完成");
- //準備插入圖片
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
- HSSFClientAnchor anchor = new HSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
- //插入圖片
- byte[] pictureData = byteArrayOutputStream.toByteArray();
- int pictureFormat = HSSFWorkbook.PICTURE_TYPE_JPEG;
- int pictureIndex = workbook.addPicture(pictureData, pictureFormat);
- patriarch.createPicture(anchor, pictureIndex);
- }catch(Exception e){
- e.printStackTrace();
- System.out.println("IO Erro:" + e.getMessage());
- }finally
- {
- if(fileOutputStream != null)
- {
- try{
- fileOutputStream.close();
- }catch(IOException io){
- io.printStackTrace();
- }
- }
- }
- }
- /**
- * 寫入圖片格式信息
- * @描述:這是一個實體類,提供了相應的接口,用於操作Excel,在任意座標處寫入數據。
- * @參數:
- * ImageInputStream imageInputStream:他接受一個外界傳入的圖片流,圖片以流形式存在。
- *
- * @用法:
- *
- *
- *
- *
- * @param dx1 :第一個cell開始的X座標
- * @param dy1 :第一個cell開始的Y座標
- * @param dx2 :第二個cell開始的X座標
- * @param dy2 :第二個cell開始的Y座標
- * @param col1 :圖片的左上角放在第幾個列cell (the column(o based); of the first cell)
- * @param row1 :圖片的左上角放在第幾個行cell (the row(o based); of the first cell)
- * @param col2 :圖片的右下角放在第幾個列cell (the column(o based); of the second cell)
- * @param row2 :圖片的右下角放在第幾個行cell (the row(o based); of the second cell)
- *
- * @author Yangcl
- */
- public void writeInTemplate(ImageInputStream imageInputStream , int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2 )
- {
- BufferedImage bufferImage = null;
- //寫入圖片格式信息
- try
- {
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- //先把讀入的圖片放到一個 ByteArrayOutputStream 中,用於產生ByteArray
- bufferImage = ImageIO.read(imageInputStream);
- ImageIO.write(bufferImage, "JPG", byteArrayOutputStream);
- System.out.println("ImageIO 寫入完成");
- //準備插入圖片
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
- HSSFClientAnchor anchor = new HSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
- //插入圖片
- byte[] pictureData = byteArrayOutputStream.toByteArray();
- int pictureFormat = HSSFWorkbook.PICTURE_TYPE_JPEG;
- int pictureIndex = workbook.addPicture(pictureData, pictureFormat);
- patriarch.createPicture(anchor, pictureIndex);
- }catch(Exception e){
- e.printStackTrace();
- System.out.println("IO Erro:" + e.getMessage());
- }finally
- {
- if(fileOutputStream != null)
- {
- try{
- fileOutputStream.close();
- }catch(IOException io){
- io.printStackTrace();
- }
- }
- }
- }
- /**
- * 保存模板
- * @描述:這個方法用於保存workbook(工作薄)中的內容,並寫入到一個Excel文件中
- * @參數:String templateFile:取得已經保存的類模板 路徑名稱
- * @用法:templateFile:String templateFile_Name1 = "C:/Tamplates/texting-1.xls"
- * TemplateAdapter ta = new TemplateAdapter();
- * ta.SaveTemplate(templateFile_Name1);
- * @param templateFile
- */
- public void SaveTemplate(String templateFile)
- {
- try{
- //建立輸出流
- fileOutputStream = new FileOutputStream(templateFile);
- workbook.write(fileOutputStream);
- }catch(Exception e){
- e.printStackTrace();
- System.out.println("IO Erro" + e.getMessage());
- }finally
- {
- if(fileOutputStream != null)
- {
- try{
- fileOutputStream.close();
- }catch(IOException io){
- io.printStackTrace();
- }
- }
- }
- }
- }