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

  1. Thanks, I’ve been searching for facts about this subject for ages and yours is the best I’ve found so far.

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

  3. Lazrszk表示:

    Привет, друзья!
    Заказать диплом ВУЗа.
    prof-komplekt.com/club/user/1035/blog/11031

  4. Diplomi_ewEa表示:

    Привет, друзья!
    Приобрести документ института вы имеете возможность у нас.
    asxdiplomik.com/kupit-diplom-novosibirsk 

  5. Trefbsx表示:

    Добрый день!
    Официальная покупка аттестата о среднем образовании в Москве и других городах
    sabordetango.org/portale/modules.php?name=Your_Account&op=userinfo&uname=TomasBisbe
    Поможем вам всегда!.

  6. Lazryhd表示:

    Привет, друзья!
    Мы готовы предложить дипломы психологов, юристов, экономистов и других профессий по приятным тарифам.
    willstonemidlevel.com/куплю-диплом-фото

  7. Today, with the fast lifestyle that everyone leads, credit cards have a big demand throughout the economy. Persons throughout every area of life are using credit card and people who not using the credit card have arranged to apply for just one. Thanks for discussing your ideas on credit cards.

  8. Uazrxav表示:

    Привет, друзья!
    Заказать диплом университета.
    weekinato.ru/kupit-diplom-ekonomte-vremya-i-dengi/

  9. скачать популярные игры на телефон бесплатно http://android-games-download.ru .

  10. видеостена для конференц зала http://videosteny-pod-kljuch.ru/ .

  11. скачать игры бесплатно на телефон скачать игры бесплатно на телефон .

  12. Dnrtfqz表示:

    Привет!
    Приобрести документ ВУЗа вы имеете возможность в нашей компании в столице.
    diploms-x24.ru/kupit-diplom-omsk
    Удачи!

  13. Trefgmt表示:

    Привет, друзья!
    Как официально приобрести аттестат 11 класса с минимальными затратами времени
    dadiler.com/купить-диплом-советы-и-рекомендации
    Поможем вам всегда!.

  14. Sazrjmu表示:

    Добрый день!
    Мы можем предложить дипломы любой профессии по доступным тарифам. Цена будет зависеть от той или иной специальности, года выпуска и университета. Всегда стараемся поддерживать для заказчиков адекватную ценовую политику. Важно, чтобы дипломы были доступными для большого количества наших граждан.
    appleincub.ru/kupit-diplom-byistryiy-i-nadezhnyiy-sposob-poluchit-obrazovanie

  15. Sazrfnv表示:

    Здравствуйте!
    Мы изготавливаем дипломы психологов, юристов, экономистов и других профессий по доступным ценам. Цена зависит от конкретной специальности, года получения и ВУЗа. Стараемся поддерживать для заказчиков адекватную ценовую политику. Важно, чтобы дипломы были доступными для подавляющей массы граждан.
    http://www.es-presto.ru/community/groups/0-0/113-kak-podobrat-nadezhnyj-magazin-gde-mozhno-kupit-diplom

  16. Mazrfqr表示:

    Добрый день!
    Официальная покупка диплома вуза с сокращенной программой обучения в Москве
    diploms-man.ru

  17. Reent表示:

    In the publishing industry, proofreaders usually check a printed “proof copy” of the text and mark corrections using specialized proofreading marks. In other fields, though, professional proofreaders often work with digital texts and make corrections directly using the track changes feature in Microsoft Word or Google Docs. As you can see, proofreading is the final stage of the editing process. It is the final check after formatting and before self-publishing or sending a manuscript to an agent or publisher. How do you become a certified proofreader? You can become a professional proofreader by earning a certificate in Editing and or Proofreading through various institutions. There are long-distance learning opportunities for at-home learners. What most people are referring to when they use the word proofreading is the process of checking a document for any kind of grammatical, typographical, or formatting errors. Proofreading should always be the last step taken before a document is published online, handed in to a professor, submitted for a job application, or otherwise shared with its intended audience.
    https://secondstreet.ru/profile/zsubalitym1988/
    For the first three years the two children shared a tutor. Now, as their interests and strengths become more divergent the client has opted to have two tutors to cover the subjects so that each can be more specialised. All our tutors have an Enhanced DBS, are referenced and ID checked, and have passed our onboarding process. Diccionario inglés-español, traductor y sitio de aprendizaje Could you point at a few specific tutorials or other instructions that you found hard to follow due to the changes that were made in the app since they were made? We are aware that there are indeed many smaller visual changes, but it’d be really useful to know which ones are especially problematic for you. This was such a good read and makes so much sense, thank you for sharing!

  18. Michaelclich表示:

    Welcome to our platform, your primary source for all the freshest reports and information on the communications landscape in the United Kingdom. Whether you’re fascinated in telecasts, radio, print, or digital media, we offer complete coverage that keeps you aware about the key changes and trends. From breaking news stories to thorough analyses, our team of seasoned journalists and industry professionals work ceaselessly to bring you the most precise and recent data – https://totalfratmove.com/articles/popular-events-of-2024-in-the-united-kingdom.html
    In addition to stories, we deliver perceptive features and opinion pieces that delve into the nuances of the communications industry. Our stories cover a broad spectrum of topics, including regulatory modifications, media ownership, and the impact of new innovations. We also showcase the successes and challenges faced by media professionals, providing a platform for voices from throughout the industry to be recognized and respected.
    Stay in touch with the pulse of the UK media scene through our frequently updated content. Whether you’re a media professional, a student, or simply a media enthusiast, our website is designed to serve to your needs and wants. Participate in our growing community of readers and make sure you’re always in the know about the dynamic and constantly changing world of media in the United Kingdom.

  19. Reent表示:

    Once they set up Business Manager, they can assign people a variety of user roles including admin roles for accessing billing information, managing accounts, making changes to assets, and inviting others to the Business Manager. If you think you have been blocked in error, contact the owner of this site for assistance. After creating a Page for your business, it’s time to make a business profile. For that, click Meta Business Suite on the left-hand side. Click the drop-down menu in your Page profile, and choose Create a Business Account. After creating a Page for your business, it’s time to make a business profile. For that, click Meta Business Suite on the left-hand side. Click the drop-down menu in your Page profile, and choose Create a Business Account.
    https://martinfdpm814722.elbloglibre.com/26634732/ww3-world-news-today
    Daily e-Edition The full power of WOWKTV on your computer is instantly available for your smartphone, tablet or feature phone, and it’s specifically tailored to your device. There’s no app to download or update, and you’ll get the full experience, instantly, on your iPhone, iPad, Android, eReader or hundreds of other devices. Enjoy rich interactive features, like full-screen video and a mobile-friendly interactive radar, all from the experienced local news team you trust. Evening e-Edition Please enter a search term. Please enter a valid zipcode. Watch for us in your inbox. Watch for us in your inbox. Thanks for signing up! Watch for us in your inbox. Please enter a search term. EXTENDED FORECAST: The \”Omega blocking\” pattern that’s helped to bring prolonged dry weather, begins to break down late in the week. This will result in showers and storms Thursday and Friday. On the back half of these systems, we may also see another round of rain to end the weekend. Temperatures look to climb above average over the weekend as well with the 80s returning.

  20. Diplomi_dwEa表示:

    Добрый день!
    Купить документ ВУЗа вы имеете возможность в нашей компании в Москве.
    ast-diplomas.com/kupit-diplom-chelyabinsk

  21. видеостены москва videosteny-pod-kljuch.ru .

發佈留言

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