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

27,076 Responses

  1. для вашего дома.
    с применением привода.
    Как выбрать правильный привод для жалюзи.
    Преимущества автоматизированного привода для жалюзи.
    Тенденции в автоматизации жалюзи с помощью привода.
    Как управлять жалюзями с помощью смартфона с использованием привода.
    Шаг за шагом по инструкции по установке привода для жалюзи.
    Экономьте время и энергию с автоматизированным приводом для жалюзи.
    Необычное применение приводов для управления жалюзями.
    Секрет уюта и удобства с автоматизированными жалюзями.
    привод жалюзи радиатора бмв https://elektrokarniz21.ru/ .

  2. NorbertKep表示:

    pharmacie en ligne pas cher: п»їpharmacie en ligne france – acheter mГ©dicament en ligne sans ordonnance

  3. Perryzoozy表示:

    acheter mГ©dicament en ligne sans ordonnance pharmacie en ligne sans ordonnance pharmacie en ligne france pas cher

  4. Jacobbep表示:

    acheter mГ©dicament en ligne sans ordonnance http://pharmaciemeilleurprix.com/# pharmacie en ligne livraison europe

  5. NorbertKep表示:

    Viagra pas cher livraison rapide france: Acheter Viagra Cialis sans ordonnance – Viagra Pfizer sans ordonnance

  6. NorbertKep表示:

    pharmacie en ligne sans ordonnance: pharmacie en ligne sans ordonnance – pharmacie en ligne france livraison internationale

  7. Richardprurf表示:

    https://tadalafilmeilleurprix.shop/# vente de mГ©dicament en ligne
    Pharmacie Internationale en ligne

  8. Richardprurf表示:

    http://tadalafilmeilleurprix.com/# pharmacie en ligne france livraison belgique
    pharmacie en ligne france livraison internationale

  9. Richardprurf表示:

    https://tadalafilmeilleurprix.shop/# pharmacie en ligne avec ordonnance
    vente de mГ©dicament en ligne

  10. Jacobbep表示:

    Pharmacie en ligne livraison Europe http://kamagrameilleurprix.com/# pharmacie en ligne france fiable

  11. Jacobbep表示:

    pharmacie en ligne france pas cher http://tadalafilmeilleurprix.com/# pharmacie en ligne pas cher

  12. Perryzoozy表示:

    Pharmacie Internationale en ligne Acheter Cialis Pharmacie sans ordonnance

  13. They look like a cool digital watch, and the colour choices are many and varied.

  14. Kevinalgon表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    лаки джет официальный
    Scores of unexploded bombs dating from World War II have been recovered from a children’s playground in northern England after a chance discovery.

    Local officials in the town of Wooler, Northumberland called in bomb disposal experts after workers involved in a planned overhaul of Scotts Play Park found unexploded ordnance, the parish council said in a statement sent to CNN on Monday.

    Two bombs were initially removed by the British Army, the UK Ministry of Defense said in a statement. The parish council was then advised that a full survey of the area was required, according to a council spokesperson.
    Bomb disposal company Brimstone Site Investigation then uncovered 65 10-pound practice bombs and smoke cartridges on the first day of works, with a further 90 practice bombs recovered on the second day.

    The company told CNN that the bombs date from World War II.

    According to the parish council, all of the bombs need to be found and removed before the park can be reopened. It said 174 devices had been found so far.

  15. VirgilBlawl表示:

    amoxicillin 500 mg price Amo Health Pharm amoxicillin online no prescription

  16. JustinTam表示:

    zithromax prescription in canada: purchase zithromax online – zithromax 500 mg

  17. JustinTam表示:

    cost generic clomid without insurance: how to buy cheap clomid without prescription – where to buy clomid no prescription

  18. Roberttic表示:

    http://zithropharm.com/# can i buy zithromax over the counter in canada

  19. Briantrozy表示:

    buy zithromax online: ZithroPharm – can i buy zithromax online

  20. Michaelnen表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    Площадка кракен
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  21. Briantrozy表示:

    amoxicillin 500mg capsule buy online: AmoHealthPharm – where can i buy amoxicillin online

  22. Briantrozy表示:

    buy cheap zithromax online: ZithroPharm – how to get zithromax

  23. Roberttic表示:

    https://doxhealthpharm.com/# can i buy doxycycline over the counter in south africa

  24. You can follow Kryz Uy on her Instagram account here.

  25. TravisCal表示:

    Most flights don’t want you joining the Mile-High Club. This company encourages it
    kraken darknet onion
    In our travel news roundup this week: the rise in solo dining, where to save money at US ski resorts, plus the Californian hot-air balloon company offering a rather cheeky package.

    Your love keeps lifting me higher
    Is it getting hot in here, or is a gas-burner propelling a dirigible above our heads?

    A California-based hot-air balloon company is offering mile-high flights – with amorous Mile-High Club privileges – over the Temecula countryside.

    Guests can enjoy the views with a whole basket to themselves – and a privacy screen separating the pilot compartment from the passenger cabin.

    The pilot, who Magical Adventure Balloon Rides promises will be wearing protective hearing gear and focused solely on flying, ascends the balloon to 5,280 feet (about 1,610 meters), which is about 2,000 feet higher than a typical recreational flight.

    While intimate clinches are usually thoroughly discouraged in the skies, the company invites you to bring your own bedding and music playlist. A complimentary Champagne breakfast is included to fuel your frolics, of whatever sort.

    Pricing for two passengers starts at $1,400. If your mantra is “the more the merrier,” each additional adult in the larger 10-person basket is $159.

    The Mile-High Club flight is just one of a host of packages on offer, from wine tours to company picnics, the rest of which are considerably more family-friendly.
    All by myself
    Sometimes it can seem like the world is full of lovers floating high on cloud nine, but don’t fret if you’re going it alone this Valentine’s season: You’re bang on trend.

    Millennials and Gen Z are breaking down the stigma attached to solo dining in an era when more Americans live alone than ever before. Some do it for convenience; some do it for freedom — either way, reservations for one are on the rise.

    Once you’ve mastered dining alone, it’s time for bigger challenges, such as walking across Saudi Arabia. British explorer Alice Morrison, who has been called “Indiana Jones for girls,” is in the middle of her five-month trek of 2,500 kilometers (about 1,550 miles).

    Others are opting for a permanent adventure. Californian Jason Bennett gave up his life in San Francisco for a new home in Colombia. Today he says his happiness is “off the charts.”

  26. VirgilBlawl表示:

    doxycycline 100mg buy online DoxHealthPharm doxycycline buy online usa

  27. JustinTam表示:

    875 mg amoxicillin cost: amoxicillin 875 mg tablet – amoxicillin 500 coupon

  28. JustinTam表示:

    how much is zithromax 250 mg: ZithroPharm – where can i buy zithromax in canada

  29. JustinTam表示:

    buy azithromycin zithromax: can i buy zithromax over the counter in canada – zithromax 500 tablet

  30. Roberttic表示:

    https://clmhealthpharm.shop/# can i order cheap clomid for sale

發佈回覆給「Jacobbep」的留言 取消回覆

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