Excel - HelloWorld

如果要將某些資料匯出成excel,常常會直接使用csv的格式,因為簡單、檔案小。但如果要做到如背景顏色、文字變化、套巨集等,csv格式就沒有那麼powerful。還好Apache POI非常的牛B,讓我們可以透過Java存取M$的東西。對工程師而言,說再多不如直接看程式碼,接下來我將透過一個簡單的範例教導大家該如何使用點POI皮毛。

我希望能夠產生如下圖的Excel檔案:

主要實作以下特徵:

  1. 產生Excel格式為xls
  2. Sheet名稱為StockSummary
  3. 第一行文字置中,其餘靠右

一個Excel檔案會對應到POI的Workbook,一個Workbook包含很多的Sheet,一個Sheet包含很多的Row,一個Row包含很多的Cell。而Cell可以透過CellStyle去決定想要顯示的樣式,包含字型(Font)、高度與寬度等。我分成三個步驟說明如何實作:

  1. 建立一個Sheet名稱為StockSummary的xls
  2. 建立資料內容
  3. 設定置中與靠右

Create Sheet

POI提供建立xls與xlsx方式,對應的Workbook實作分別為HSSFWorkbook與XSSFWorkbook;Sheet的部分可以透過Workbook去建立。最後再建立OutputStream並透過Workbook的write寫入檔案就可以產生一個最陽春xls格式的excel;讀取則要透過WorkbookFactory的create。

	static public void createHSSFWorkbook(String aFileName){
		Workbook wb = new HSSFWorkbook();
		FileOutputStream fileOutputStream = null;
		try {
			wb.createSheet("SimpleSheet");
 
			fileOutputStream = new FileOutputStream(aFileName);
			wb.write(fileOutputStream);
		} catch(Exception e){
			logger.error("", e);
		} finally {
			Cleaner.close(fileOutputStream);
		}
	}

Create Content

在建立Sheet後,我們可以透過它去建立Row。在Excel上看到的1,2,3,4…就是Row,而A,B,C,D為Collumn,Row與Collumn交會如1A就是Cell。POI提供Row與Cell的操作。如以下程式碼,我們僅需要指定要建立的Row與Cell index,就可以建立我們想要的Cell,接著再透過setCellValue設定目標值。目標值其實也包含許多格式,setCellValue有許多的Overloading,會根據你傳入的型態決定Excel中的格式。

			Row headRow = sheet.createRow(0);
			String[] headerStr = { "股號", "年", "月", "開立發票總金額", "營業收入淨額", "合併營業收入淨額"};
			for( int i = 0 ; i < headerStr.length ; i++ ){
				Cell cell = headRow.createCell(i);
				cell.setCellValue(headerStr[i]);
 
			}
 
			Row dataRow = sheet.createRow(1);
			String[] DataStr = { "1012", "5", "2", "111,111", "222,222", "333,333"};
			for( int i = 0 ; i < DataStr.length ; i++ ){
				Cell cell = dataRow.createCell(i);
				cell.setCellValue(DataStr[i]);
 
			}

Set Align

在POI中,格式都是透過CellStyle去設定。為了達成我們的目標,我們需要建立Align Center與Align Right的CellStyle,最後在建立Cell後,再透過Cell的setCellStyle設定即可。

			CellStyle align_center_style = wb.createCellStyle();
			align_center_style.setAlignment(CellStyle.ALIGN_CENTER);
			align_center_style.setVerticalAlignment(CellStyle.ALIGN_CENTER);
 
			CellStyle align_right_style = wb.createCellStyle();
			align_right_style.setAlignment(CellStyle.ALIGN_RIGHT);
			align_right_style.setVerticalAlignment(CellStyle.ALIGN_RIGHT);
 
			Row headRow = sheet.createRow(0);
			String[] headerStr = { "股號", "年", "月", "開立發票總金額", "營業收入淨額", "合併營業收入淨額"};
			for( int i = 0 ; i < headerStr.length ; i++ ){
				Cell cell = headRow.createCell(i);
				cell.setCellValue(headerStr[i]);
				cell.setCellStyle(align_center_style);
			}
 
			Row dataRow = sheet.createRow(1);
			String[] DataStr = { "1012", "5", "2", "111,111", "222,222", "333,333"};
			for( int i = 0 ; i < DataStr.length ; i++ ){
				Cell cell = dataRow.createCell(i);
				cell.setCellValue(DataStr[i]);
				cell.setCellStyle(align_right_style);
			}

很簡單吧! 不可否認POI真的很牛B,就目前我所知的Excel功能它幾乎都實作了(也許是因為我知道的不多)! 之後有時間我再把常用的東西分享給大家!
PS. 假如是很複雜的樣式,不如先建立樣版,再透過讀取接著建立的方式實作喔!