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

  1. Aifoni_oiSt表示:

    ремонт айфона с выездом https://iphonepochinka.by .

  2. Aifoni_bnSt表示:

    ремонт iphone минск ремонт iphone минск .

  3. Aifoni_vbSt表示:

    ремонт телефонов айфон ремонт телефонов айфон .

  4. Aifoni_mdSt表示:

    ремонт айфона цены http://www.iphonepochinka.by/ .

  5. Aifoni_veSt表示:

    сервисный центр айфон в минске сервисный центр айфон в минске .

  6. As melhores slots estao aqui Blaze

  7. Aifoni_ogSt表示:

    центр apple ремонт iphone http://www.iphonepochinka.by .

  8. Jogue no cassino de maior prestigio Blaze

  9. Phillipspult表示:

    Roberto Firmino Barbosa de Oliveira https://roberto-firmino.prostoprosport-br.com Brazilian footballer, attacking midfielder, forward for the Saudi club “Al-Ahli”. Firmino is a graduate of the Brazilian club KRB, from where he moved to Figueirense in 2007. In June 2015 he moved to Liverpool for 41 million euros.

  10. Shawntriek表示:

    Larry Joe Bird https://larry-bird.prostoprosport-br.com American basketball player who spent his entire professional career in the NBA ” Boston Celtics.” Olympic champion (1992), champion of the 1977 Universiade, 3-time NBA champion (1981, 1984, 1986), three times recognized as MVP of the season in the NBA (1984, 1985, 1986), 10 times included in the symbolic teams of the season (1980-88 – first team, 1990 – second team).

  11. Aifoni_rxSt表示:

    выездной ремонт iphone выездной ремонт iphone .

  12. Divirta-se no cassino mais confiavel Blaze

  13. Gustavosar表示:

    Экспертиза ремонта в квартире https://remnovostroi.ru проводится для оценки качества выполненных работ, соответствия требованиям безопасности и стандартам строительства. Специалисты проверяют используемые материалы, исполнение работ, конструктивные особенности, безопасность, внешний вид и эстетику ремонта. По результатам экспертизы составляется экспертное заключение с оценкой качества и рекомендациями по устранению недостатков.

  14. Walterclali表示:

    Quincy Anton Promes https://quincy-promes.prostoprosport-br.com Dutch footballer, attacking midfielder and forward for Spartak Moscow . He played for the Dutch national team. He won his first major award in 2017, when Spartak became the champion of Russia.

  15. Cassinos com as melhores promocoes Blaze

  16. Descubra o melhor cassino online Blaze

  17. A lot of whatever you point out is astonishingly legitimate and that makes me wonder why I had not looked at this with this light before. Your article really did turn the light on for me as far as this specific subject matter goes. Nonetheless there is 1 point I am not really too cozy with and while I attempt to reconcile that with the core theme of your point, let me see exactly what all the rest of the subscribers have to say.Nicely done.

  18. акустическое оборудование для актового зала акустическое оборудование для актового зала .

  19. Peterkef表示:

    Mohammed Khalil Ibrahim Al-Owais https://mohammed-alowais.prostoprosport-ar.com is a Saudi professional footballer who plays as a goalkeeper for the national team Saudi Arabia and Al-Hilal. He is known for his quick reflexes and alertness at the gate.

  20. GeorgeHib表示:

    Kevin De Bruyne https://kevin-de-bruyne.prostoprosport-ar.com Belgian footballer, midfielder of the Manchester club City” and the Belgian national team. A graduate of the football clubs “Ghent” and “Genk”. In 2008 he began his adult career, making his debut with Genk.

  21. оборудование для актовых залов оборудование для актовых залов .

  22. музыкальное оборудование для актового зала oborudovanie-aktovogo-zala13.ru .

  23. оборудование для сцены актового зала https://oborudovanie-aktovogo-zala13.ru .

  24. музыкальное оборудование для актового зала oborudovanie-aktovogo-zala13.ru .

  25. оборудование актового зала оборудование актового зала .

  26. оборудование актового зала оборудование актового зала .

  27. оборудование для актового зала оборудование для актового зала .

  28. оборудование для актовых залов оборудование для актовых залов .

發佈留言

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