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

  1. Lakidjet_rwoi表示:

    лаки джет на деньги лаки джет на деньги .

  2. Lakidjet_rhoi表示:

    lucky jet официальный сайт http://www.1win-luckyjet-ru.ru .

  3. Tommyphito表示:

    What’s up, its nice article about media print, we all understand media is a fantastic source of facts.
    https://forumkoldovstva.listbb.ru/viewtopic.php?f=37&t=14862

  4. Lakidjet_jaoi表示:

    lucky jet на деньги 1win-luckyjet-ru.ru .

  5. Georgedealp表示:

    атака титанов в хорошем качестве https://ataka-titanov-anime.ru

  6. Lakidjet_mhoi表示:

    lucky jet на деньги 1win-luckyjet-ru.ru .

  7. Tommyphito表示:

    I savor, lead to I discovered exactly what I was having a look for. You have ended my 4 day long hunt! God Bless you man. Have a nice day. Bye
    http://rolevikionline.g-talk.ru/viewtopic.php?f=21&t=2631

  8. Thanks for making me to obtain new ideas about personal computers. I also hold the belief that certain of the best ways to maintain your laptop in perfect condition is a hard plastic case, or maybe shell, that fits over the top of the computer. Most of these protective gear tend to be model targeted since they are made to fit perfectly over the natural covering. You can buy them directly from the vendor, or through third party places if they are for your notebook, however only a few laptop could have a spend on the market. Yet again, thanks for your suggestions.

  9. Ses表示:

    There are no tips or tricks when it comes to bonus buys. Unlike sign-up incentives like free spins and starting funds, the buy bonus of slots is a core component of the game’s design. It adds a fresh dynamic to standard slot gameplay, giving players the ability to tailor the gameplay to suit their preferences. We build slots, scratchcards and instant win games for the largest brands and governments in the iGaming industry. Our games are powered by our industry-leading Remote Gaming Server platform. The features of slots have been evolving throughout the years. The kinds of symbols have changed as well which is why the majority of slots come with Wilds, Scatters, and a bonus buy feature, which adds to overall gameplay. The best slots for bonus buy will enable you to enter the bonus round in exchange for extra charge from your balance. Continue reading this article to find more about this type of slots.
    http://save-the-nation-institute.com/2019/11/28/%E7%AC%AC10%E5%9B%9E%E3%83%8F%E3%83%AF%E3%82%A4%E9%81%A0%E5%BE%81-%E7%AC%AC60%E5%9B%9E%E5%85%A8%E3%83%8F%E3%83%AF%E3%82%A4%E5%B7%9E%E7%A9%BA%E6%89%8B%E9%81%93%E9%81%B8%E6%89%8B%E6%A8%A9%E5%A4%A7/
    Sevenwinds Casino, Lodge & Conference Center Though we’re all well-acquainted with Jeep’s iconic slotted front grille, a few questions remain. Firstly, how many slots are in a Jeep’s grille? Secondly, where did the beloved design come from? And thirdly, what do the slots represent? Our experts answer these questions and more in the following article! We have crafted each and every detail with extensive care and our tool is power-packed yet easy to use. If you ever wished to create your own Casino Slot Machine Game but don’t have a knowledge of programming or the time required to build everything from scratch, with our help you can get started very easily. Power-packed yet easy to use, our Slot Game Kit will save you hundreds of development hours and help you reach your digital dreams faster than ever.

  10. Danielpesia表示:

    купить квартиру в казани от застройщика https://nedvizhimost16.ru

  11. WilliamSisse表示:

    купить квартиру от застройщика недорого https://kvartiru-kupit-kzn.ru

  12. Tommyphito表示:

    Прокат автомобиля в Минске – на час, день или более длительный период – в наше время не роскошь, а необходимость.В большом городе человек без машины, как без рук – ничего не успеть!
    аренда авто на сутки

  13. Danielpesia表示:

    купить квартиру недорого https://nedvizhimost16.ru

  14. Aviator_dvPi表示:

    aviator game online real money aviator game online real money .

  15. WilliamSisse表示:

    купить квартиру от застройщика https://kvartiru-kupit-kzn.ru

  16. куда пожаловаться на сайт мошенников http://pozhalovatsya-na-moshennikov.ru/ .

  17. пожаловаться на мошенников пожаловаться на мошенников .

  18. пожаловаться на сайт мошенников пожаловаться на сайт мошенников .

  19. пожаловаться на мошенников пожаловаться на мошенников .

  20. кому пожаловаться на сайт мошенников pozhalovatsya-na-moshennikov.ru .

  21. ArthurMeary表示:

    купить квартиру в казани https://kupit-kvartirukzn.ru

  22. пожаловаться на телефонных мошенников http://www.pozhalovatsya-na-moshennikov.ru .

  23. Usglfi表示:

    purchase griseofulvin for sale – dipyridamole 25mg cost lopid online order

  24. Patricktug表示:

    https://aisory.tech – платформа для создания AI Telegram-ботов. Наделяйте своих ботов способностями к естественному диалогу, генерации уникального контента и решению аналитических задач. Простой конструктор платформы делает создание умных чат-ботов доступным для любой компании.

  25. ArthurMeary表示:

    жк купить квартиру от застройщика https://kupit-kvartirukzn.ru

發佈留言

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