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

25,788 Responses

  1. RobertCex表示:

    yasal oyun siteleri: casibom guncel giris – 2025 deneme bonusu veren bahis siteleri casibom1st.com

  2. casino表示:

    469179 254372But wanna admit that this is extremely helpful , Thanks for taking your time to write this. 630729

  3. Weldonsib表示:

    sweet bonanza slot: sweet bonanza oyna – sweet bonanza slot sweetbonanza1st.shop

  4. Lily Brown表示:

    You may be able to borrow more and enjoy better interest rates by taking out a loan secured on your property. Review current offers today.

  5. GarrettMom表示:

    jackpot play nedir casibom mobil giris deneme bonusu veren bahis siteleri 2025 casibom1st.shop

  6. Josephfax表示:

    cali weed delivery in prague buy cannabis in prague

  7. BradyGem表示:

    casino siteleri: dede kumar sitesi – casino siteleri 2025 casinositeleri1st.com

  8. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервис центры бытовой техники москва
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. James Green表示:

    You may be able to secure larger loans and enjoy lower monthly repayments by using your home’s equity. Review current offers today.

  10. BradyGem表示:

    yeni gГјncel deneme bonusu veren siteler: casibom 1st – en iyi bahis sitesi hangisi casibom1st.com

  11. GarrettMom表示:

    sweet bonanza demo sweet bonanza giris sweet bonanza giris sweetbonanza1st.com

  12. JeffryAcani表示:

    Hidden Link Placement in Established Content Hubs
    Hi there! If you’re reading this, chances are you’re looking for a way to boost your website’s visibility in Google. I understand — mastering SEO might seem intimidating, especially with so many “quick-fix” services out there claiming guaranteed results that rarely materialize. That’s why I want to share my strategy with you. It’s not just another cookie-cutter service — it’s a personalized strategy designed to deliver real, measurable results.

    I specialize in building link pyramids that combine Tier 1, Tier 2, and Tier 3 backlinks. Imagine building a sturdy base for a skyscraper. Without a solid base, everything else crumbles. My goal is to boost your primary domain’s credibility in a way that aligns with search engine algorithms and actually works.

    What Makes Me Different?
    I’ll cut to the chase: I’ve been in the SEO game for years, and I’ve experienced the full spectrum — successful strategies and outright scams. I’ve worked with clients who wasted hundreds (sometimes thousands) on services that claimed foolproof results but resulted in search engine bans. That’s why I decided to redefine the process.

    I focus on authoritative dofollow links from reputable sources. The majority of top-layer backlinks in my strategy are dofollow because they offer maximum SEO value. And here’s the kicker — you’ll get this premium service at significantly reduced rates (costing just 200–350 USD). How does wasting money help? Save your hard-earned cash ?? in something that actually works.

    My Unique Value Proposition

    High Authority Guest Posts
    I avoid low-quality directories. Absolutely not. I curate only the most reputable guest post sites — sites boasting high trust flow (TF). These are the kinds of sites that give your website a serious boost.
    Unique, Handwritten Content
    Low-quality writing harms credibility. It’s detrimental to your brand. That’s why every article I create is plagiarism-free, captivating, and customized for your industry. Whether it’s for Web 2.0 properties, I guarantee Copyscape-passed content that supports your strategy organically. Pure quality, zero filler — content that converts.
    Multi-Tiered Authority System
    Here’s where things get interesting. My method goes beyond basics by incorporating Tier 2 and Tier 3 support links. This layered approach strengthens the effect of your main connections, driving sustainable growth for your money site. Imagine an avalanche effect, compounding over time.
    Diverse Link Sources
    Google loves diversity, so I use a mix high-authority sources: media channels, directories, and niche forums. This isn’t about cheating algorithms; it’s about creating enduring value.
    Complete Honesty
    When you work with me, you’ll see every detail. I provide a thorough documentation, including full administrative rights. Clear communication, no surprises. You’ll track every backlink source and their impact on rankings.
    Real-World Proof
    Let me share something personal: A few years ago, I worked with a client who was frustrated because their website wasn’t ranking despite countless strategies. They’d tried various “experts”, but results were elusive. When they came to me, I took the time to understand their goals. Together, we built a custom link pyramid tailored to their niche. Soon, rankings climbed, and they started seeing real conversions. That’s the kind of success I strive to deliver with every client.

    Let’s build your path to the top Contact me now and turn search engines into your ally. ??

  13. BradyGem表示:

    internet kumar oyunu: casibom guncel giris – deneme bonusu veren yeni casino siteleri casibom1st.com

  14. introduced表示:

    Greetings! Very helpful advice in this particular article! It is the little changes that produce the most important changes. Many thanks for sharing!

  15. Weldonsib表示:

    en saДџlam bahis siteleri: casibom giris – bonus veren site casibom1st.com

  16. RobertCex表示:

    sweet bonanza giris: sweet bonanza giris – sweet bonanza siteleri sweetbonanza1st.shop

  17. Davidled表示:

    https://sweetbonanza1st.shop/# sweet bonanza siteleri

  18. JeffryAcani表示:

    Hidden Link Placement in Established Content Hubs
    Hello! If this message caught your attention, you’re probably seeking strategies to enhance your online presence. I understand — mastering SEO might seem intimidating, especially with so many “quick-fix” services out there claiming guaranteed results that rarely materialize. That’s why I want to share my method with you. It’s not just another cookie-cutter service — it’s a bespoke approach designed to deliver tangible growth.

    I specialize in building link pyramids that combine Tier 1, Tier 2, and Tier 3 backlinks. Think of it like constructing a strong foundation for your house. Without a solid base, everything else crumbles. My goal is to boost your primary domain’s credibility in a way that mimics organic growth and delivers results.

    Why Should You Trust Me?
    To be straightforward: I’ve been in the search engine optimization industry for years, and I’ve witnessed every trend — ethical practices and black-hat tactics. I’ve worked with clients who poured resources on services that claimed foolproof results but ended up getting them penalized. That’s why I decided to redefine the process.

    I focus on premium follow-backlinks from reputable sources. The majority of top-layer backlinks in my strategy are dofollow because they pack the biggest punch. And here’s the kicker — you’ll get this top-tier offering at significantly reduced rates (costing just 200–350 USD). How does wasting money help? Invest wisely in something that delivers real ROI.

    The Secret Sauce

    Elite Guest Blogging
    I avoid low-quality directories. Never. I handpick only the top-tier platforms — sites boasting high trust flow (TF). These are the kinds of sites that elevate your domain’s credibility.
    Original, Custom-Crafted Articles
    Let’s face it — spun or generic content sticks out like a sore thumb. It’s boring, unnatural, and frankly, a waste of time. That’s why every post I create is plagiarism-free, captivating, and customized for your industry. Whether it’s for private blog networks (PBNs), I guarantee originality reports that blends seamlessly into your campaign. No shortcuts, no fluff — just high-quality writing that gets results.
    Pyramid-Structured Backlinks
    Here’s where things get powerful. My method builds depth by incorporating mid-level and foundational backlinks. This structured system strengthens the effect of your primary backlinks, driving sustainable growth for your money site. Think of it like a snowball rolling downhill — it starts small but gains momentum.
    Varied Backlink Portfolio
    Google loves diversity, so I leverage multiple high-authority sources: media channels, directories, and niche forums. This isn’t about gaming the system; it’s about establishing long-term authority.
    Full Transparency
    When you work with me, you’ll know exactly what you’re getting. I provide a detailed link report, including access credentials. Full disclosure at every step. You’ll monitor each placement and their impact on rankings.
    Real-World Proof
    Here’s a real example: A few years ago, I worked with a client who was struggling to gain traction despite months of effort. They’d tried several services, but results were elusive. When they came to me, I took the time to understand their goals. A personalized approach was implemented. Within a few months, their traffic doubled, and they boosted lead generation. That’s the kind of outcome you can expect with every client.

    Let’s build your path to the top Drop me a line today and let’s make Google work for you. ??

  19. Weldonsib表示:

    sweet bonanza yorumlar: sweet bonanza demo – sweet bonanza 1st sweetbonanza1st.shop

  20. Davidled表示:

    https://sweetbonanza1st.com/# sweet bonanza siteleri

  21. BradyGem表示:

    guvenilir casino siteleri: casino siteleri – lisansl? casino siteleri casinositeleri1st.com

  22. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:ремонт крупногабаритной техники в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  23. Davidled表示:

    http://casinositeleri1st.com/# lisansl? casino siteleri

  24. photoshopnews表示:

    When I originally left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and from now on whenever a comment is added I get 4 emails with the same comment. Is there a means you are able to remove me from that service? Appreciate it.

  25. RobertCex表示:

    gГјvenilir casino bahis siteleri: casibom mobil giris – casino siteleri 2024 casibom1st.com

  26. BradyGem表示:

    en gГјvenilir bahis: casibom mobil giris – kumar sitesi casibom1st.com

發佈回覆給「Davidled」的留言 取消回覆

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