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

17,957 Responses

  1. наркологическая скорая помощь москва [url=http://www.guryevsk.forum24.ru/?1-2-0-00000041-000-0-0-1730874532]наркологическая скорая помощь москва [/url] .

  2. как вызвать наркологическую скорую помощь в москве как вызвать наркологическую скорую помощь в москве .

  3. Diplomi_stpi表示:

    купить диплом настоящий образованиях купить диплом настоящий образованиях .

  4. minswap表示:

    Thank you for sharing indeed great looking !

  5. BruceGaf表示:

    [url=https://victoriamotorsinc.com/]online auto auction[/url] mercedes-benz vin lookup

  6. Diplomi_lvml表示:

    где купить диплом пту 2orik-diploms.ru .

  7. Donaldabula表示:

    what is the cheapest ed medication [url=http://fastpillseasy.com/#]FastPillsEasy[/url] erectile dysfunction drugs online

  8. RogerFaf表示:

    http://fastpillsformen.com/# sildenafil online

  9. BrettTIT表示:

    Viagra generic over the counter: FastPillsForMen.com – Sildenafil 100mg price

  10. скорая наркологическая помощь [url=http://www.ukroenergo.ukrbb.net/viewtopic.php?f=13&t=21400]скорая наркологическая помощь[/url] .

  11. наркологическая скорая [url=www.airlady.forum24.ru/?1-8-0-00000030-000-0-0-1730874450/]www.airlady.forum24.ru/?1-8-0-00000030-000-0-0-1730874450/[/url] .

  12. Donaldabula表示:

    cheap ed cheap erection pills erectile dysfunction online

  13. вывод из запоя ростов на дону на дому вывод из запоя ростов на дону на дому .

  14. DonaldJex表示:

    Ukrainian President Volodymyr Zelensky will meet US President Joe Biden and Vice President Kamala Harris in Washington on Thursday. Leon Neal/Getty Images
    CNN

    Ukrainian President Volodymyr Zelensky’s visit to the White House on Thursday could be his final chance to convince a receptive American president of his country’s war aims.
    [url=https://megaweb-8.com]megaweb20.at[/url]
    The precise details of the “victory plan” Zelensky plans to present in separate meetings to President Joe Biden and Vice President Kamala Harris are unknown, having been closely held until they are presented to the American leaders.

    But according to people briefed on its broad contours, the plan reflects the Ukrainian leader’s urgent appeals for more immediate help countering Russia’s invasion. Zelensky is also poised to push for long-term security guarantees that could withstand changes in American leadership ahead of what is widely expected to be a close presidential election between Harris and former President Donald Trump.

    The plan, people familiar with it said, acts as Zelensky’s response to growing war weariness even among his staunchest of western allies. It will make the case that Ukraine can still win — and does not need to cede Russian-seized territory for the fighting to end — if enough assistance is rushed in.

    That includes again asking permission to fire Western provided long-range weapons deeper into Russian territory, a line Biden once was loathe to cross but which he’s recently appeared more open to as he has come under growing pressure to relent.

    Even if Biden decides to allow the long-range fires, it’s unclear whether the change in policy would be announced publicly.

    Biden is usually apt to take his time making decisions about providing Ukraine new capabilities. But with November’s election potentially portending a major change in American approach to the war if Trump were to win, Ukrainian officials — and many American ones — believe there is little time to waste.
    megaweb19.com
    https://megaweb-6.com
    Trump has claimed he will be able to “settle” the war upon taking office and has suggested he’ll end US support for Kyiv’s war effort.

    “Those cities are gone, they’re gone, and we continue to give billions of dollars to a man who refused to make a deal, Zelensky. There was no deal that he could have made that wouldn’t have been better than the situation you have right now. You have a country that has been obliterated, not possible to be rebuilt,” Trump said during a campaign speech in Mint Hill, North Carolina, on Wednesday.

    Comments like those have lent new weight to Thursday’s Oval Office talks, according to American and European officials, who have described an imperative to surge assistance to Ukraine while Biden is still in office.

    As part of Zelensky’s visit, the US is expected to announce a major new security package, thought it will likely delay the shipping of the equipment due to inventory shortages, CNN previously reported according to two US officials. On Wednesday, the US announced a package of $375 million.

    The president previewed Zelensky’s visit to the White House a day beforehand, declaring on the margins of the United Nations General Assembly his administration was “determined to ensure that Ukraine has what it needs to prevail in fight for survival.”
    [url=https://megaweb-8at.com]megaweb12.at[/url]
    “Tomorrow, I will announce a series of actions to accelerate support for Ukraine’s military – but we know Ukraine’s future victory is about more than what happens on the battlefield, it’s also about what Ukrainians do make the most of a free and independent future, which so many have sacrificed so much for,” he said.

  15. Wilbertsit表示:

    Ukrainian President Volodymyr Zelensky will meet US President Joe Biden and Vice President Kamala Harris in Washington on Thursday. Leon Neal/Getty Images
    CNN

    Ukrainian President Volodymyr Zelensky’s visit to the White House on Thursday could be his final chance to convince a receptive American president of his country’s war aims.
    [url=https://megaweb-5at.com]megaweb18.at[/url]
    The precise details of the “victory plan” Zelensky plans to present in separate meetings to President Joe Biden and Vice President Kamala Harris are unknown, having been closely held until they are presented to the American leaders.

    But according to people briefed on its broad contours, the plan reflects the Ukrainian leader’s urgent appeals for more immediate help countering Russia’s invasion. Zelensky is also poised to push for long-term security guarantees that could withstand changes in American leadership ahead of what is widely expected to be a close presidential election between Harris and former President Donald Trump.

    The plan, people familiar with it said, acts as Zelensky’s response to growing war weariness even among his staunchest of western allies. It will make the case that Ukraine can still win — and does not need to cede Russian-seized territory for the fighting to end — if enough assistance is rushed in.

    That includes again asking permission to fire Western provided long-range weapons deeper into Russian territory, a line Biden once was loathe to cross but which he’s recently appeared more open to as he has come under growing pressure to relent.

    Even if Biden decides to allow the long-range fires, it’s unclear whether the change in policy would be announced publicly.

    Biden is usually apt to take his time making decisions about providing Ukraine new capabilities. But with November’s election potentially portending a major change in American approach to the war if Trump were to win, Ukrainian officials — and many American ones — believe there is little time to waste.
    megaweb16.com
    https://mega555kf7lsmb54yd6etzginolhxxi4ytdoma2rf77ngq5fhcnid.com
    Trump has claimed he will be able to “settle” the war upon taking office and has suggested he’ll end US support for Kyiv’s war effort.

    “Those cities are gone, they’re gone, and we continue to give billions of dollars to a man who refused to make a deal, Zelensky. There was no deal that he could have made that wouldn’t have been better than the situation you have right now. You have a country that has been obliterated, not possible to be rebuilt,” Trump said during a campaign speech in Mint Hill, North Carolina, on Wednesday.

    Comments like those have lent new weight to Thursday’s Oval Office talks, according to American and European officials, who have described an imperative to surge assistance to Ukraine while Biden is still in office.

    As part of Zelensky’s visit, the US is expected to announce a major new security package, thought it will likely delay the shipping of the equipment due to inventory shortages, CNN previously reported according to two US officials. On Wednesday, the US announced a package of $375 million.

    The president previewed Zelensky’s visit to the White House a day beforehand, declaring on the margins of the United Nations General Assembly his administration was “determined to ensure that Ukraine has what it needs to prevail in fight for survival.”
    [url=https://megaweb-15at.com]megaweb com[/url]
    “Tomorrow, I will announce a series of actions to accelerate support for Ukraine’s military – but we know Ukraine’s future victory is about more than what happens on the battlefield, it’s also about what Ukrainians do make the most of a free and independent future, which so many have sacrificed so much for,” he said.

  16. This tracker bundle consists of the whole lot you need in your journey towards a debt free life!

  17. вывод из запоя ростовская область вывод из запоя ростовская область .

  18. The Hudson Wasp does feel like a natural accompaniment to the Hudson Hornet, doesn’t it?

  19. срочная наркологическая помощь в москве [url=http://www.ukroenergo.ukrbb.net/viewtopic.php?f=13&t=21400]срочная наркологическая помощь в москве[/url] .

發佈留言

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