透過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...

8,443 Responses

  1. Hello! This post couldn’t be written any better! Reading
    this post reminds me of my good old room mate! He always kept chatting about this.
    I will forward this write-up to him. Fairly certain he will have
    a good read. Thank you for sharing!

  2. hqigkovn表示:

    https://hydroxychloroquinex.com/ hydroxychloroquine 200mg tablets

  3. deesse表示:

    viagra like pills viagra buy online ireland cheap mexico viagra

  4. hcomztqy表示:

    http://erythromycin1m.com/# side effects of erythromycin ophthalmic ointment

  5. Slonmob表示:

    nrzgy

    cic9s

    p0tk

  6. rtiutfjc表示:

    http://erythromycinn.com/# erythromycin ophthalmic ointment usp 0.5

  7. mebezgpc表示:

    side effects of erythromycin http://erythromycin1m.com/#

  8. washginn表示:

    2 to 4 GB of available hard disk space
    Client Requirements for Windows XP Service Pack 2, Windows Server 2003 Service Pack 2
    1.0 GHz processor
    256 MB of RAM
    2 to 4 GB of available hard disk space
    Microsoft Customer Experience Improvement Program (CEIP)

    A:

    It’s a dated product. I came across a review of it in this thread.

    A:

    IMO, the best Microsoft software suite is simply Windows Server 2008 https://versiis.com/3805/infinitynotepad-crack-product-key-full-free-download-latest-2022/
    50e0806aeb washginn

  9. It’s going to be end of mine day, however before end I am reading this enormous article to improve my knowledge.

    My webpage เครื่องกำจัดขยะ

  10. lorealay表示:

    Universal Audio Converter is a powerful audio converter tool that can easily and quickly convert files from one format to another. It can be used to convert between audio/video files, or any other format, such as rm, m4a, mp3, wav and many other. In addition, it features an automatic mode, so you don’t have to manually set parameters like Encoder, Sample Rate and Bit Rate. Also, the UI is quite friendly and easy to learn for non https://atmosphere-residence.ro/free-itunes-backup-extractor-torrent-free-download-latest/
    50e0806aeb lorealay

  11. pirfig表示:

    Features
    This tool offers multiple features:
    Install; Uninstall; Hide; UnHide; Start Process; Add processes; Wait for process; RunProcessTo; KillProcess; Set process icon; Set process details; View process details.

    External links

    Category:Windows-only software
    Category:Windows-only freeware.write(‘>>’) https://adsocialnetwork.com/upload/files/2022/06/CSnJk5tCidYJbyh84ceG_06_f72a63f60b8e498a6a1e373b42600165_file.pdf
    50e0806aeb pirfig

  12. darfab表示:

     This package will please all animal lovers.

    Interface

    The Animals Tracks is a nice icon collection featuring various animal footprint images. All the icons included in the pack are in ICO format. If you like animals, you will surely enjoy this iconset!

    Replace the standard icons of your files and folders with this fun pack of animal foot print icons. Some of them feature some species you might not have heard of before.

    If you like animals, you will surely enjoy https://www.magicalcambodia.com/wp-content/uploads/2022/06/fermbrie.pdf
    50e0806aeb darfab

  13. patrdei表示:

    Graphics on the Internet being a thing, the PNG format is used as by some and Chrome likes to use it by default, along with a bunch of other reasons. Ok, now that’s out of the way, lets discuss desktop tools that can help convert PNG files with speed.

    1. Kraken

    The one and only option on my list for the process is Kraken by the folks over at FilePig. Kraken offers a simple and fast GUI which is easy to https://pouss-mooc.fr/2022/06/06/butterfly-formerly-menses-with-product-key-for-windows-updated-2022/
    50e0806aeb patrdei

  14. shatan表示:

    Bundled with AMD/ATI Radeon and NVIDIA GPU drivers
    The program is bundled with graphics drivers from AMD and NVIDIA. Therefore, users are already set to work with new higher resolutions without having to figure out any of the above details on their own.
    Bundled with NVIDIA’s GPU drivers
    The NVIDIA SDK, included in the ‘SDK-P01.exe’ files, enables users to override the default resolutions of any NVIDIA GPUs. Using a.inf file inside the https://www.sosho.pk/upload/files/2022/06/RepFiRWDNhe9nZ3Ph6OC_06_0471268bc0035b0278c33922c38fd671_file.pdf
    50e0806aeb shatan

  15. rowosm表示:

    An additional benefit can be achieved if you combine virtual application deployment with mobile application and mobile game publishing.
    Turbo Studio offers an extensive bundle of features. You can go ahead and take advantage of its under-the-hood wizard, as it offers plenty of solutions on how you can package an application for deployment in one package.

    Good state

    Final Thoughts

    Registering a domain name for your business online in addition to a.co.UK extension provides many advantages, such as https://dawnintheworld.net/wp-content/uploads/2022/06/PDF_Glue.pdf
    50e0806aeb rowosm

  16. spramad表示:

    Do you like to convert a Word document and preserve text and photos on your hard disk? Try this tool and give it a go. You will surely come back for more!Emma Mendes

    Director

    Shanghai and Prague, PRC

    Photo: Alexandra Lepikova

    1. Why did you return to the United States?

    Our (domestic) market access in the United States is ready and we have signed the contract with a highly specific distributor http://www.chineseqingmen.org/clarion-to-java-compiler-crack-final-2022/
    50e0806aeb spramad

  17. walcer表示:

    You can run the.exe folder of EdCafe Editor (Ede Cafe Editor for Mac) on both Mac OSX and Windows or even Linux. Make sure you unzip the file before running it.

    EdCafe Editor for Mac and Windows is a minimum version of EdCafe Editor, which is a free online high quality English editor and word processor that you can use to edit and format all kinds of text files from different web pages to traditional documents without any additional software https://www.sosho.pk/upload/files/2022/06/fArObdQxWmCxgW4iuEbD_06_dc45d4d00054a5db087f9cdc79aa4025_file.pdf
    50e0806aeb walcer

  18. marraog表示:

    Powered by Freebirds (v 2.8), an award-winning multimedia editing software. Some of Freebirds’ features include:

    Advanced Video Tools. – (Unique Photo Editor 2.0 for Photographers) All in One Photo Edit to add stunning effects to your photos. You can use the powerful, easy-to-use tools to soften the skin on your subjects, adjust the tone of the whole image, add special effects such as vignettes, horizontal lines, https://serv.biokic.asu.edu/ecdysis/checklists/checklist.php?clid=3566
    50e0806aeb marraog

發佈留言

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