透過Java解析Excel檔案

也是一個工作中遇到的情境,很多單位想讓內部人員利用Excel維護資料(因為維護上比較簡單方便),且想讓這份資料透過網頁呈現給一般網友閱讀,所以整體後端的流程應該是:

  1. 將維護的Excel透過網頁介面上傳
  2. 將上傳的Excel轉換成XML
  3. 網頁去讀取這份XML來呈現

透過以上的三個步驟,就可以完成客戶想要效果。

本範例展示的是讀取Excel的XLS格式(新版Excel為XLSX格式),並轉換成陣列的方法(寫入XML在前面的範例就有了),我們選用讀取Excel的Library是Apache POI,而檔內已經有以下的資料,其中Total是公式欄位,計算Price x Quantity:

IDNamePriceQuantityTotal
100001產品名稱110550
100002產品名稱22010200
100003產品名稱33015450

以下是讀取的程式範例:

package CDIT.stanley;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
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 excelToXMLFullSample {
	
	static ArrayList<ArrayList<String>> excelData = new ArrayList<ArrayList<String>>();
	
	public static void main (String[] args) throws FileNotFoundException{
		
		excelData.clear();
	    
	    String xlsPath = "C:\\Projects\\Javas\\sample.xls";
	    InputStream inputStream = null;
	    inputStream = new FileInputStream (xlsPath);
		POIFSFileSystem fileSystem = null;
	    try {
	        fileSystem = new POIFSFileSystem (inputStream);
			@SuppressWarnings("resource")
			HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
	        HSSFSheet sheet = workBook.getSheetAt (0);
	        Iterator<?> rows = sheet.rowIterator ();
	        
	        while (rows.hasNext ()){
	            HSSFRow row = (HSSFRow) rows.next();
	            Iterator<?> cells = row.cellIterator ();

	            ArrayList<String> rowData = new ArrayList<String>();
	            
	            while (cells.hasNext ()){
	                HSSFCell cell = (HSSFCell) cells.next();
	                
	                switch (cell.getCellTypeEnum()){
		                case STRING :{
		                    rowData.add(cell.getStringCellValue());
		                    break;
		                }
		                case NUMERIC : {
		                    rowData.add((int)cell.getNumericCellValue() + "");
			                break;
		                }
		                case FORMULA :{
		                	switch(cell.getCachedFormulaResultTypeEnum()) {
			                    case STRING:
			                    	rowData.add(cell.getStringCellValue ());
			                        break;
			                    case NUMERIC:
			                    	rowData.add((int)cell.getNumericCellValue() + "");
			                        break;
					default:
						rowData.add("");
						break;
		                	}
		                }		                
			default:
				rowData.add("");
				break;
	                }
	            }
	            excelData.add(rowData);
	        }
	    } catch(IOException e){
	        System.out.println("IOException " + e.getMessage());
	        System.out.println("轉換失敗,請檢查Excel檔案與格式是否正確");
	    }
	    for(int i=0 ; i<excelData.size(); i++){
	    	System.out.println("Excel Row "+ i +" Data : " + excelData.get(i));
	    }
	    
	}
}

程式會把Excel內的資料轉換為ArrayList,輸出內容如下:

Excel Row 0 Data : [Product ID, Product Name, Product Price, Quantity, Total]
Excel Row 1 Data : [100001, 產品名稱1, 10, 5, 50, ]
Excel Row 2 Data : [100002, 產品名稱2, 20, 10, 200, ]
Excel Row 3 Data : [100003, 產品名稱3, 30, 15, 450, ]

You may also like...

14,588 Responses

  1. Zamok_xdKl表示:

    открыть замок услуга http://vskrytie-zamkov-moskva113.ru/ .

  2. FobertWen表示:

    What’s up to all, how is everything, I think every one is getting more from this web page, and your views are good in favor of new visitors.

    forexallnews.com/broker-profile/ace-investing 
    wine.historic.ru/books/c0007_1.shtml 
    http://www.tenku.eu/pl/wpisy/nowa-porcja-onigiri?page=59 
    russiafreedom.ru/question/titan-s-teplakom/ 
    ilonka.ru/user/robertgneida/ 

  3. Zamok_vbKl表示:

    вскрыть замок цена https://vskrytie-zamkov-moskva113.ru/ .

  4. Zamok_jnKl表示:

    вскрыть дверь фирмы http://vskrytie-zamkov-moskva113.ru .

  5. EddieMouck表示:

    Kylian Mbappe https://kylianmbappe.prostoprosport-ar.com is a French footballer, striker for Paris Saint-Germain and captain of the French national team. He began playing football in the semi-professional club Bondi, which plays in the lower leagues of France. He was noticed by Monaco scouts, which he joined in 2015 and that same year, at the age of 16, he made his debut for the Monegasques. The youngest debutant and goal scorer in the club’s history.

  6. Edwarddig表示:

    Pin Up Azerbaycan ?Onlayn Kazino: Pin Up Kazino ?Onlayn – Pin-up Giris

  7. LeonardScome表示:

    Vinicius Junior https://viniciusjunior.prostoprosport-ar.com is a Brazilian and Spanish footballer who plays as a striker for Real Madrid and the Brazilian national team. Junior became the first player in the history of Los Blancos, born in 2000, to play an official match and score a goal.

  8. RicardoGlolo表示:

    мониторинг серверов л2
    Сервера л2

  9. RicardoGlolo表示:

    мониторинг серверов ла2
    Сервера ла2

  10. RicardoGlolo表示:

    сервера ла2
    Сервера л2

  11. Edwarddig表示:

    Pin Up Azerbaycan ?Onlayn Kazino: pin-up360 – Pin-Up Casino

  12. FobertWen表示:

    Hello, every time i used to check blog posts here in the early hours in the daylight, for the reason that i like to gain knowledge of more and more.

    1-carat.ru/ 
    petkit.com.cn/member/index.php?uid=ehalipa&action=viewarchives&aid=6644 
    startspresto.ru/dannye/pluginclass/cbblogs?action=blogs&func=show&id=22 
    scientistsufo.ru/page/14 
    fastpas.info/ 

  13. Edwarddig表示:

    Pin Up Kazino ?Onlayn: Pin Up Azerbaycan – pin-up360

  14. RobertSax表示:

    https://autolux-azerbaijan.com/# pin-up 141 casino

  15. Russell Grebs表示:

    The unique viewpoints you bring to The writing are as captivating as The online presence. Always a pleasure.

  16. Edwarddig表示:

    ?Onlayn Kazino: Pin Up Azerbaycan ?Onlayn Kazino – Pin Up

  17. RobertSax表示:

    https://autolux-azerbaijan.com/# Pin Up Azerbaycan ?Onlayn Kazino

  18. Andrew Alday表示:

    The work is truly inspirational. It’s as if you’ve found a way to whisper sweet nothings to my intellect.

  19. Agueda Dinovi表示:

    Provoked thought and taught me something new, as if my brain needed more exercise.

  20. Edwarddig表示:

    pin-up360: Pin up 306 casino – Pin Up Azerbaycan

  21. Lewisslund表示:

    Hi! This is kind of off topic but I need some help from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to begin. Do you have any tips or suggestions? Appreciate it

    hrcspb.ru/page/page60.html 
    zakon122.ru/promotion/ 
    dbecosmeticos.com.br/blog/suplemento-alimentar-hair-supply/montazh-kondicionera-moskva.ru 
    http://www.sendungsverfolgung24.org/forum/topic/dfdg234dsfsd/?part=9324 
    travel.bizph.com/viewtopic.php?f=127&p=1031687 

  22. Diplomi_smEr表示:

    образование купить диплом какие образование купить диплом какие .

  23. Diplomi_ulEr表示:

    купить аттестат с реестром купить аттестат с реестром .

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。