Java實現Excel編輯之POI


最後編輯時間:2015-02-2817:54

 

JAVA通常有兩種方法來操作Excel,分別是POI和JExcelAPI,而且都是開源的。

 

POI參考:

 

JExcelAPI參考:

http://www.oschina.net/code/snippet_126103_3553

http://blog.csdn.net/aking21alinjuju/article/details/5996110

 

 

應用場景:

* excel的第一個sheet首行添加標題,宋體,18號,加粗,在內容所有列合併居中;

* 在最後添加一行,格式與初始第一行一樣,字體顏色爲藍色;

* A列單元格統計記錄數,GH列單元格使用公式統計數值,貨幣格式呈現;

 

POI使用JAR:poi-3.8-20120326.jar, poi-ooxml-3.8-20120326.jar , poi-ooxml-schemas-3.8-20120326.jar ,xmlbeans-2.3.jar 

代碼:

 

package charlie.utils.excel;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

 

import org.apache.poi.hssf.util.CellRangeAddress;

import org.apache.poi.hssf.util.HSSFColor;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.Font;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.ss.usermodel.WorkbookFactory;

 

 

/**

 * @author CharlieChen

 * @DateTime 2015-1-5 上午11:46:43

 * @version 1.0

 */

@SuppressWarnings("deprecation")

public class PoiUtil {

 

   /**

    * @param args

    */

   public static void main(String[] args) {

     

      PoiUtil poiUtil = new PoiUtil();

      String excelPath = "D:/temp/test/abc.xlsx";   

      Workbook wb = poiUtil.getExcelWorkBook(excelPath);

     

      String reName = "D:/temp/test/temp.xlsx";

      poiUtil.editExcel(wb,reName);

 

   }

  

   /**

    * excel的第一個sheet首行添加標題,宋體,18號,加粗,在內容所有列合併居中

    * 在最後添加一行,格式與初始第一行一樣,字體顏色爲藍色,

    * A列單元格統計記錄數,GH列單元格使用公式統計數值,貨幣形式呈現

    * @param wb

    * @param reName

    */

   public void editExcel(Workbook wb,String reName){   

      Sheet sheet = wb.getSheetAt(0);

      int maxRow = sheet.getLastRowNum();//獲取行數

      Row firstRow = sheet.getRow(0);//獲取第一行

      int maxColumn = firstRow.getLastCellNum();//獲取列數 

      sheet.shiftRows(0, maxRow, 1);//整體下移一行,相當於在首行插入一行           

      Row titleRow = sheet.createRow(0);//新增行

      //增加合併區域,首行從第一列到有內容的最後一列

      sheet.addMergedRegion(new CellRangeAddress(0,0,0,maxColumn-1));  

      //合併單元格

      Cell titleCell = titleRow.createCell(0);

      CellStyle cellStyle = wb.createCellStyle();

      titleCell.setCellValue("顯示內容");     

      Font font = wb.createFont();

      font.setFontName("宋體");//字體

      font.setFontHeightInPoints((short)18);//字體大小

      font.setBoldweight(Font.BOLDWEIGHT_BOLD);//加粗

      cellStyle.setFont(font);

      cellStyle.setAlignment(CellStyle.ALIGN_CENTER);//居中對齊

      titleCell.setCellStyle(cellStyle);

     

      Row lastRow = sheet.createRow(maxRow + 1);

      //最後新增一行

      int count = maxRow - 1;    

      Font lastFont = wb.createFont();

       lastFont.setFontName("宋體");//字體

       lastFont.setFontHeightInPoints((short)11);

       //顏色設置爲藍色        

       lastFont.setColor(HSSFColor.BLUE.index);      

       CellStyle lastStyle = wb.createCellStyle();

       lastStyle.cloneStyleFrom(firstRow.getCell(0).getCellStyle());

       lastStyle.setFont(lastFont);

      

       //構造最後一行

       for(int i=0;i<maxColumn;i++){

          lastRow.createCell(i).setCellStyle(lastStyle);

       }

       //填數據

       lastRow.getCell(0).setCellValue("記錄數:" + count);

       //份額餘額統計

       lastRow.getCell(6).setCellType(Cell.CELL_TYPE_FORMULA);

       lastRow.getCell(6).setCellFormula("sum(G3:G"+(maxRow+1)+")");

       //貨幣格式顯示

       CellStyle currencyStyle = wb.createCellStyle(); 

       currencyStyle.cloneStyleFrom(lastStyle);

       currencyStyle.setDataFormat((short)4);   

       lastRow.getCell(6).setCellStyle(currencyStyle);

       //最新市值統計

       lastRow.getCell(7).setCellType(Cell.CELL_TYPE_FORMULA);

       lastRow.getCell(7).setCellFormula("sum(H3:H"+(maxRow+1)+")");

       lastRow.getCell(7).setCellStyle(currencyStyle);

      

      //保存到文件

      FileOutputStream is;

      try {

         is = new FileOutputStream(reName);        

           wb.write(is);  

           is.close();

           System.out.println("保存完成");

      } catch (FileNotFoundException e) {

         e.printStackTrace();

      } catch (IOException e) {

         e.printStackTrace();

      }

   }

  

   /**

    * @method讀取0307版本的excel的公共方法,根據文件的路徑創建Workbook對象

    * @param filePath 文件全路徑

    */

   public  Workbook getExcelWorkBook(String filePath) {

      InputStream ins = null;

      Workbook book = null;

      try {

         ins=new FileInputStream(new File(filePath));        

         book = WorkbookFactory.create(ins);

         ins.close();

         return book;

      } catch (FileNotFoundException e1) {

         e1.printStackTrace();

      } catch (InvalidFormatException e) {

         e.printStackTrace();

      } catch (IOException e) {

         e.printStackTrace();

      } finally {

         if (ins != null) {

            try {

                ins.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

         }

      }

      return null;

   }

}

貨幣格式顯示參考:

http://blog.csdn.net/zxcvbnmluton/article/details/6066916        

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