透過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...

8,797 Responses

  1. Yfhnth表示:

    hydrochlorothiazide pill – order lisinopril 2.5mg pills bisoprolol 5mg tablet

  2. Davidtes表示:

    buy 20mg lisinopril price of lisinopril generic lisinopril 12.5

  3. RandallTaulp表示:

    buy cipro online canada: cipro generic – antibiotics cipro

  4. 1win879piodo表示:

    Самая Надежная Букмекерская контора – 1win

  5. Charlesunili表示:

    SEO раскрутка сайта в топ https://seositejob.ru/ Яндекс и Google от профессионалов.

  6. WilliamRhype表示:

    https://cytotec.club/# buy cytotec online fast delivery

  7. Davidtes表示:

    buy cytotec online fast delivery purchase cytotec buy cytotec over the counter

  8. RandallTaulp表示:

    buy cytotec over the counter: buy cytotec online fast delivery – buy cytotec over the counter

  9. RandallTaulp表示:

    cytotec pills buy online: buy cytotec online fast delivery – buy cytotec over the counter

  10. Harrydup表示:

    What’s up, all the time i used to check webpage posts here early in the dawn, as i enjoy to find out more and more.
    https://englishmax.ru/

  11. Лучшая Букмекерская контора, рекомендую 1win

  12. RandallTaulp表示:

    ciprofloxacin 500 mg tablet price: antibiotics cipro – buy cipro

  13. Ronaldpsymn表示:

    https://cytotec.club/# Misoprostol 200 mg buy online

  14. FobertWen表示:

    В современном мире, где диплом – это начало удачной карьеры в любом направлении, многие пытаются найти максимально быстрый и простой путь получения образования. Наличие официального документа об образовании трудно переоценить. Ведь именно диплом открывает дверь перед людьми, желающими начать профессиональную деятельность или продолжить обучение в ВУЗе.
    В данном контексте наша компания предлагает максимально быстро получить любой необходимый документ. Вы имеете возможность купить диплом, что становится выгодным решением для всех, кто не смог завершить образование или утратил документ. Любой диплом изготавливается с особой тщательностью, вниманием к мельчайшим нюансам, чтобы на выходе получился 100% оригинальный документ.
    Плюсы данного подхода заключаются не только в том, что можно быстро получить диплом. Весь процесс организован просто и легко, с нашей поддержкой. От выбора подходящего образца документа до грамотного заполнения личной информации и доставки в любой регион России — все будет находиться под полным контролем наших специалистов.
    Всем, кто хочет найти оперативный способ получения необходимого документа, наша компания готова предложить отличное решение. Купить диплом – это значит избежать продолжительного обучения и сразу перейти к важным целям: к поступлению в ВУЗ или к началу успешной карьеры.

    https://diploman-russiyan.com

  15. Ronaldpsymn表示:

    https://cytotec.club/# Misoprostol 200 mg buy online

  16. Davidtes表示:

    cytotec abortion pill buy misoprostol over the counter buy cytotec in usa

  17. WilliamRhype表示:

    https://cytotec.club/# п»їcytotec pills online

  18. RandallTaulp表示:

    cytotec pills online: purchase cytotec – buy cytotec online fast delivery

  19. RandallTaulp表示:

    buy cytotec pills: buy cytotec online fast delivery – buy cytotec in usa

  20. WilliamRhype表示:

    https://cytotec.club/# purchase cytotec

  21. Ronaldpsymn表示:

    https://cytotec.club/# buy cytotec pills

  22. RandallTaulp表示:

    cost of generic propecia without insurance: cost of generic propecia – get generic propecia

  23. sitemap.xml表示:

    hey there and thbank you foor yokur inbformation – I’ve crtainly picdked up anything nnew frm right here.
    I diid however expertise some echnical isesues usingg tuis web site, aas I experienced too reload the sife a lot
    off timjes revious to I could get it tto loadd properly.
    I hadd been wndering iif ykur weeb hot iss OK? Not that I amm
    complaining, but slow loading instaances timds will ofen affect your placemsnt inn google andd could damage your high-qualityscore
    if ads andd marketing wwith Adwords. Well I’m adding
    this RSS tto myy emzil aand can loook oout forr
    much moe oof your respextive fascinating content. Ensre tthat youu update this again soon.

  24. Топовая Букмекерская контора в мире 1win

  25. Davidtes表示:

    tamoxifen bone pain tamoxifen mechanism of action raloxifene vs tamoxifen

  26. Great site ! I recommend everyone to watch it!paris escort

  27. WilliamRhype表示:

    https://nolvadex.life/# tamoxifen

發佈留言

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