透過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,685 Responses

  1. There are actually plenty of details like that to take into consideration. That could be a great point to bring up. I supply the ideas above as basic inspiration however clearly there are questions like the one you carry up where a very powerful factor will probably be working in honest good faith. I don?t know if best practices have emerged round issues like that, however I am sure that your job is clearly recognized as a good game. Each boys and girls feel the influence of only a second?s pleasure, for the remainder of their lives.

  2. Armandoknot表示:

    Как поднять настроение с помощью коротких шуток

  3. Armandoknot表示:

    Как развить чувство юмора с помощью коротких шуток

  4. DouglasHoapy表示:

    1xBet New Promo Code https://actuchomage.org/includes/wkl/code_promo_69.html
    1xBet frequently releases new promo codes that provide users with updated bonuses and promotions. These codes can include anything from free bets to deposit matches and are available to both new and existing users.

  5. HeathZex表示:

    pharmacie en ligne: Pharmacies en ligne certifiees – Pharmacie en ligne livraison Europe

  6. Charlesrab表示:

    Viagra homme prix en pharmacie sans ordonnance Viagra sans ordonnance 24h Viagra sans ordonnance 24h Amazon

  7. DouglasHoapy表示:

    Promo Codes for 1xBet https://idematapp.com/wp-content/pages/1xbet_promo_codes_free_bonus_offers.html
    1xBet regularly releases promo codes that provide users with bonuses like free bets, deposit matches, or free spins. These codes are a great way to boost your bankroll and increase your chances of winning.

  8. I have been browsing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as you did, the web will be much more useful than ever before.

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

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

  11. Kennethlam表示:

    панели армстронг http://armstrong-tiles24.ru/

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

  13. HeathZex表示:

    п»їpharmacie en ligne france: cialis generique – pharmacie en ligne france pas cher

  14. DouglasHoapy表示:

    1xBet Sign Up Bonus https://actuchomage.org/includes/wkl/code_promo_69.html
    The 1xBet sign-up bonus is a special offer available to new users when they register on the platform. This bonus usually includes a deposit match, giving new users extra funds to start betting on sports or casino games.

  15. Gartandabsex表示:

    КОРОТКИЕ ШУТКИ И АНЕКДОТЫ
    Как развить чувство юмора

  16. Gartandabsex表示:

    КОРОТКИЕ ШУТКИ И АНЕКДОТЫ
    Как уместно шутить

  17. HeathZex表示:

    pharmacie en ligne fiable: Cialis generique achat en ligne – pharmacie en ligne france livraison belgique

  18. Charlesrab表示:

    pharmacie en ligne france pas cher cialis sans ordonnance acheter mГ©dicament en ligne sans ordonnance

  19. DouglasHoapy表示:

    1xBet Free Promo Codes https://idematapp.com/wp-content/pages/1xbet_promo_codes_free_bonus_offers.html
    1xBet offers free promo codes that provide users with bonuses without requiring a deposit. These codes are a great way to try out the platform and win real money without risking your own funds.

  20. DouglasHoapy表示:

    Promocode for 1xBet https://actuchomage.org/includes/wkl/code_promo_69.html
    Promocodes for 1xBet unlock various bonuses, including free bets, deposit matches, and free spins. These codes are often shared through promotions, affiliate sites, or social media and can be entered during registration or deposit.

  21. Jeffreygef表示:

    Arrowheads reveal the presence of a mysterious army in Europe’s oldest battle
    жесткий анальный секс
    Today, the lush, green valley surrounding the Tollense River in northeast Germany appears to be a serene place to appreciate nature.

    But to archaeologists, the Tollense Valley is considered Europe’s oldest battlefield.

    An amateur archaeologist first spotted a bone sticking out of the riverbank in 1996.

    A series of ongoing site excavations since 2008 has shown that the thousands of bones and hundreds of weapons preserved by the valley’s undisturbed environment were part of a large-scale battle 3,250 years ago.

    The biggest mysteries that researchers aim to uncover are why the battle occurred and who fought in it. These are questions that they are now one step closer to answering.
    ozens of bronze and flint arrowheads recovered from the Tollense Valley are revealing details about the able-bodied warriors who fought in the Bronze Age battle.

    The research team analyzed and compared the arrowheads, some of which were still embedded in the remains of the fallen. While many of these weapons were locally produced, some bearing different shapes came from a region that now includes modern Bavaria and Moravia.

    The outliers’ presence suggests that a southern army clashed with local tribes in the valley, and researchers suspect the conflict began at a key landmark along the river.

    Back to the future
    Scientists are harnessing the power of artificial intelligence to detect hidden archaeological sites buried below the sand of the sprawling Rub‘ al-Khali desert.

    The desert spans 250,000 square miles (650,000 square kilometers) on the Arabian Peninsula, and its name translates to “the Empty Quarter” in English. To unravel the secrets of the desolate terrain, researchers are combining machine learning with a satellite imagery technique that uses radio waves to spot objects that may be concealed beneath surfaces.

    The technology will be tested in October when excavations assess whether predicted structures are present at the Saruq Al Hadid complex in Dubai, United Arab Emirates.

    Separately, an AI-assisted analysis uncovered a trove of ancient symbols in Peru’s Nazca Desert, nearly doubling the number of known geoglyphs, or stone and gravel arranged into giant shapes that depict animals, humans and geometric designs.

  22. Jamestiz表示:

    Я всегда верил в «Бест Вей», ведь это была возможность для тысяч простых людей получить жилье, что казалось невозможным с нынешними банковскими условиями. А теперь, когда всё это дело раздули, становится очевидно, кому это выгодно. Я не верю, что кооператив мог делать что-то нелегальное. Это обычная схема уничтожения неугодных. Видимо, власть имущие решили зачистить всех, кто не играет по их правилам. Центробанк, конечно, хочет контролировать всё и вся, чтобы люди больше зависели от банков, а не могли самостоятельно решать свои проблемы. И эта грязная игра со стороны органов, с давлением, блокировками счетов и обысками у простых пайщиков — просто позор! На таких людей, как мы, вымещают злость за то, что мы не хотим идти в кабалу к банкам. Я верю, что мы пройдем через это и кооператив снова начнет работать для нас.

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

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

  25. HeathZex表示:

    Viagra homme prix en pharmacie: Sildenafil Viagra – Acheter Sildenafil 100mg sans ordonnance

  26. JamesBuice表示:

    mexican rx online: medication from mexico – buying prescription drugs in mexico
    medication from mexico pharmacy

  27. Gartandabsex表示:

    Как развеселить друга с помощью смешных приколов

發佈留言

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