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

  1. PhilipTaine表示:

    Pedro Gonzalez Lopez https://pedri.prostoprosport-ar.com better known as Pedri, is a Spanish footballer who plays as an attacking midfielder for Barcelona and the Spanish national team. Bronze medalist of the 2020 European Championship, as well as the best young player of this tournament. Silver medalist at the 2020 Olympic Games in Tokyo. At the age of 18, he was included in the list of 30 football players nominated for the 2021 Ballon d’Or.

  2. EddieHer表示:

    Mohamed Salah https://mohamedsalah.prostoprosport-ar.com is an Egyptian footballer who plays as a forward for the English club Liverpool and the Egyptian national team. Considered one of the best football players in the world. Three-time winner of the English Premier League Golden Boot: in 2018 (alone), 2019 (along with Sadio Mane and Pierre-Emerick Aubameyang) and 2022 (along with Son Heung-min).

  3. AngelCheMO表示:

    волчонок смотреть на русском в хорошем https://volchonok-tv.ru

  4. FobertWen表示:

    That is really fascinating, You’re an excessively professional blogger. I have joined your feed and stay up for in quest of extra of your magnificent post. Additionally, I have shared your site in my social networks

    musictech.gr/forum/viewtopic.php?t=682 
    uapa.com.hk/forum/home.php?mod=space&uid=292023&do=profile 
    recept-food.ru/page/3 
    kids-news.ru/page/3 
    diaocbinhduong.org/2018/phuc-dat-connect-214901pr.html 

  5. AnthonyNob表示:

    Robert Lewandowski https://robertlewandowski.prostoprosport-ar.com is a Polish footballer, forward for the Spanish club Barcelona and captain of the Polish national team. Considered one of the best strikers in the world. Knight of the Commander’s Cross of the Order of the Renaissance of Poland.

  6. Saiti_hekr表示:

    продвижение сайтов в москве в топ продвижение сайтов в москве в топ .

  7. Saiti_jnkr表示:

    продвижение сайтов в москве яндекс продвижение сайтов в москве яндекс .

  8. Saiti_htkr表示:

    продвижение сайтов в москве заказать https://prodvizhenie-sajtov-v-moskve117.ru .

  9. Saiti_vpkr表示:

    продвижение сайтов в москве и россии продвижение сайтов в москве и россии .

  10. Saiti_xykr表示:

    продвижение сайтов в москве цена продвижение сайтов в москве цена .

  11. MyronLem表示:

    Портал о здоровье
    https://www.rezus.ru и здоровом образе жизни, рекомендации врачей и полезные сервисы. Простые рекомендации для укрепления здоровья и повышения качества жизни.

  12. MyronLem表示:

    Портал о здоровье https://www.rezus.ru и здоровом образе жизни, рекомендации врачей и полезные сервисы. Простые рекомендации для укрепления здоровья и повышения качества жизни.

  13. RamonViaps表示:

    Toni Kroos https://tonikroos.prostoprosport-ar.com is a German footballer who plays as a central midfielder for Real Madrid and the German national team. World champion 2014. The first German player in history to win the UEFA Champions League six times.

  14. MyronLem表示:

    Портал о здоровье https://rezus.ru и здоровом образе жизни, рекомендации врачей и полезные сервисы. Простые рекомендации для укрепления здоровья и повышения качества жизни.

  15. Danieldob表示:

    Всем привет! Может кто знает, где почитатьразные статьи о недвижимости? Сейчас читаю https://417-017.ru

  16. Saiti_vbkr表示:

    создание и продвижение сайтов в москве я топ сайт создание и продвижение сайтов в москве я топ сайт .

  17. Cassino com pagamentos rapidos Blaze

  18. Wonderful goods from you, man. I have understand your stuff previous to and you are just extremely excellent. I actually like what you have acquired here, certainly like what you are saying and the way in which you say it. You make it enjoyable and you still take care of to keep it wise. I can not wait to read far more from you. This is really a tremendous web site.

  19. Edwarddig表示:

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

  20. DavidLam表示:

    Victor James Osimhen https://victorosimhen.prostoprosport-ar.com is a Nigerian footballer who plays as a forward for the Italian club Napoli and the Nigerian national team. In 2015, he was recognized as the best football player in Africa among players under 17 according to the Confederation of African Football.

  21. Ganhe muito no melhor cassino Blaze

  22. Zamok_afKl表示:

    открыть и поменять замок vskrytie-zamkov-moskva113.ru .

  23. RobertSax表示:

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

  24. HarryKam表示:

    Karim Benzema https://karimbenzema.prostoprosport-ar.com is a French footballer who plays as a striker for the Saudi Arabian club Al-Ittihad. He played for the French national team, for which he played 97 matches and scored 37 goals. At the age of 17, he became one of the best reserve players, scoring three dozen goals per season.

  25. Zamok_ukKl表示:

    вскрытие замков москва дешево http://www.vskrytie-zamkov-moskva113.ru .

  26. Zamok_svKl表示:

    служба вскрыть замков и дверей http://vskrytie-zamkov-moskva113.ru/ .

  27. Zamok_dkKl表示:

    вскрытие замков межкомнатных дверей https://vskrytie-zamkov-moskva113.ru .

  28. Zamok_mhKl表示:

    вскрытие замков межкомнатных дверей http://www.vskrytie-zamkov-moskva113.ru .

發佈留言

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