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

27,083 Responses

  1. ZackaryGer表示:

    http://pinuprus.pro/# пин ап вход

  2. RobertApozy表示:

    в долг под расписку – кредит, смотреть онлайн бесплатно

  3. Elmerbuils表示:

    pin up casino: pin up azerbaycan – pin up az

  4. RobertApozy表示:

    кредит – ломбард, банки

  5. Ismaelendut表示:

    Sablier is built for builders, teams, and DAOs. With powerful Sablier token vesting, Sablier mirror integration, and Sablier crypto tools, itтАЩs the go-to for real-time finance. Backed by the trusted Sablier protocol and Sablier Labs, you can stream confidently on Sablier Ethereum. Need to claim? Use Sablier Claim or explore the Sablier app to manage it all. Visit https://sablier.cc and experience financial automation like never before!

  6. RobertApozy表示:

    взять займ – смотреть онлайн бесплатно, смотреть фильмы онлайн

  7. BrianStani表示:

    вавада казино: вавада зеркало – vavada casino

  8. JamesMaf表示:

    Say hello to Instadapp—the ultimate DeFi hub! Whether you’re using Instadapp ETH, Instadapp DAI, or Instadapp WBTC, the Instadapp App gives you seamless control with advanced Instadapp Governance features. Stake with confidence, manage your INST token, and explore opportunities like the Instadapp Airdrop. Need help? Learn how to use Instadapp and discover the power of DeFi Smart Accounts (DSA). Instadapp login today at http://instaoapp.com and level up your strategy now!

  9. Richardfek表示:

    вавада официальный сайт vavada vavada вход

  10. Ismaelfer表示:

    For newest news you have to pay a visit world-wide-web and on the web I found this site as a finest site for latest updates.
    https://padhunga.com/bi-linzy-v-farakh-perevahy-vykorystannya.html

  11. Richardproto表示:

    площадка для продажи аккаунтов биржа аккаунтов

  12. KennethKex表示:

    pin up вход: пин ап зеркало – пин ап вход

  13. Peteremorn表示:

    платформа для покупки аккаунтов платформа для покупки аккаунтов

  14. VernonPap表示:

    Looking to stake on Solana? Marinade Finance is leading the charge with trusted, non-custodial Marinade liquid staking. Stake with ease using the Marinade app and earn yield through Marinade mSOL—all while keeping control of your assets. Curious about Marinade Finance review? Users love the performance, transparency, and safety. Want to know how to Marinade Stake SOL? It’s simple—connect your wallet and start staking. Ready to earn? Visit https://marinade.ink and boost your Marinade Yield today!

  15. KennethKex表示:

    вавада казино: вавада – vavada вход

  16. Elmerbuils表示:

    вавада казино: вавада казино – вавада

  17. Carter Graft表示:

    You’re spot on with this observation! I read something very similar on https://vua88.deal/, which helped me see this issue from a fresh perspective.

  18. CliftonAntep表示:

    лазерная эпиляция бровей у мужчин лазерная эпиляция паха у мужчин

  19. Richardknile表示:

    лазерная эпиляция подмышек сколько лазерная эпиляция

  20. ZackaryGer表示:

    http://pinupaz.top/# pin up azerbaycan

  21. Автоматика Somfy — комфорт и безопасность
    Автоматика Somfy Автоматика Somfy . Прокарниз

  22. DwayneRoP表示:

    Curious about next-gen DeFi? Sky Money is transforming savings and rewards through the powerful Sky Protocol. From SKY token rewards to smart MKR to SKY conversion, the Sky ecosystem is designed for performance and transparency. With integrated Sky Savings Rate and full support for sky ETH and sky Ethereum, it’s built to grow. Want to know more? The Sky Atlas and Sky Stars program show you the way. Ready to earn? Visit https://skymoney.net and unlock your Sky rewards today!

  23. ZackaryGer表示:

    https://vavadavhod.tech/# вавада казино

  24. An interesting discussion is definitely worth comment. I do believe that you should write more about this subject, it may not be a taboo matter but generally folks don’t discuss these subjects. To the next! Best wishes.

  25. Jamestonse表示:

    RingExchange is here to redefine crypto trading. With deep liquidity from the RingX Aggregator and a smooth Ring Exchange DEX interface, users enjoy top-tier execution across chains. Use the Ring Exchange tutorial to get started, and take full advantage of Ring Exchange crypto tools. From RING crypto to the trusted Ring Exchange BNB Chain support, it’s built to scale. Curious about ProtocolRing? It’s all part of the vision. Visit https://ringexchange.org and explore Ring Exchange DeFi today!

  26. Elmerbuils表示:

    пин ап казино официальный сайт: pin up вход – пин ап казино официальный сайт

發佈回覆給「gym flooring abu dhabi」的留言 取消回覆

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