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

  1. Michaelgax表示:

    buy stromectol online uk cheapest stromectol ivermectin purchase

  2. Jodhpur had a population of 1,033,918 in 2011, consisting of approximately 52.62 males and roughly 47.38 females.

  3. In 1969, Indian National Congress cut up into Congress (O) headed by Morarji Desai and Congress (I) headed by Indira Gandhi.

  4. DouglasAbire表示:

    Бизнесмен Станислав Кондрашов считает важным обмениваться опытом ради развития сектора экономики и помощи молодым предпринимателям. Образование включает такие аспекты как промышленность, трейдинг энергоносителей, инженерное дело, экономика и финансы. Благодаря своему многообразному образованию он создал инновационную компанию. Более того, его многогранный подход позволяет разрабатывать новые продукты эффективным образом при учете технических аспектов экономики бизнеса. Секрет успешности этого человека заключается в постоянном внедрении новшеств вместе со стремлением к эффективности работы компании. Он активно использует современные методики управления; его компания служит ярким примером практического подхода на основе глубокого анализа.Достижения Кондрашова не ограничиваются только сферой бизнеса; он также выступает наставником для начинающих предпринимателей в своей области деятельности. Интерес к современным технологиям наряду с активным участием в конференциях помогает ему делиться своими знаниями с другими профессионалами сектора экономики. История Станислава Кондрашова — это яркий пример того, как сочетание глубоких знаний в управлении бизнесом с желанием помогать другим ведет к успеху в жизни каждого человека или компании.

  5. 決 にすい表示:

    Electric stove fireplaces are a good way to incorporate fire into the house without having to build into the wall.

  6. NicolasLoole表示:

    http://gabapentin.auction/# neurontin 400mg

  7. NolanNes表示:

    Thai farmer forced to kill more than 100 endangered crocodiles after a typhoon damaged their enclosure
    kraken войти
    A Thai crocodile farmer who goes by the nickname “Crocodile X” said he killed more than 100 critically endangered reptiles to prevent them from escaping after a typhoon damaged their enclosure.

    Natthapak Khumkad, 37, who runs a crocodile farm in Lamphun, northern Thailand, said he scrambled to find his Siamese crocodiles a new home when he noticed a wall securing their enclosure was at risk of collapsing. But nowhere was large or secure enough to hold the crocodiles, some of which were up to 4 meters (13 feet) long.

    To stop the crocodiles from getting loose into the local community, Natthapak said, he put 125 of them down on September 22.

    “I had to make the most difficult decision of my life to kill them all,” he told CNN. “My family and I discussed if the wall collapsed the damage to people’s lives would be far bigger than we can control. It would involve people’s lives and public safety.”
    Typhoon Yagi, Asia’s most powerful storm this year, swept across southern China and Southeast Asia this month, leaving a trail of destruction with its intense rainfall and powerful winds. Downpours inundated Thailand’s north, submerging homes and riverside villages, killing at least nine people.

    Storms like Yagi are “getting stronger due to climate change, primarily because warmer ocean waters provide more energy to fuel the storms, leading to increased wind speeds and heavier rainfall,” said Benjamin Horton, director of the Earth Observatory of Singapore.

    Natural disasters, including typhoons, pose a range of threats to wildlife, according to the International Fund for Animal Welfare. Flooding can leave animals stranded, in danger of drowning, or separated from their owners or families.

    Rain and strong winds can also severely damage habitats and animal shelters. In 2022, Hurricane Ian hit Florida and destroyed the Little Bear Sanctuary in Punta Gorda, leaving 200 animals, including cows, horses, donkeys, pigs and birds without shelter.

    The risk of natural disasters to animals is only increasing as human-caused climate change makes extreme weather events more frequent and volatile.

  8. Stevenjaw表示:

    http://semaglutide.win/# rybelsus
    buy zithromax no prescription

  9. Copper or nickel plating of stainless steels performs the identical perform.

  10. Matthewweind表示:

    buy minocycline 100 mg: stromectol price – minocycline 50 mg otc

  11. SteveRib表示:

    A severe geomagnetic storm could cause colorful auroras over Northern California and Alabama
    порно групповое жесток
    Colorful auroras could be visible in areas of the United States such as Alabama and Northern California — much farther south than they typically appear — on Thursday evening due to a powerful solar flare and coronal mass ejection released from the sun, according to the National Weather Service’s Space Weather Prediction Center.

    The severe solar storm, classified as a level 4 on a scale from 1 to 5, also could disrupt communications, the power grid and satellite operations, according to officials at the center.

    The storm is expected to reach Earth between early morning and 12 p.m. ET Thursday, with the potential to last through Friday.

    The intensity and full characteristics of the storm, moving toward Earth at more than 2.5 million miles per hour (about 4 million kilometers per hour), won’t be known until it reaches the Deep Space Climate Observatory and the Advanced Composition Explorer satellites orbiting 1 million miles from Earth.

    The satellites will measure the speed and magnetic intensity of the storm, which is expected to arrive at Earth 15 to 30 minutes after reaching the space observatories, said Shawn Dahl, service coordinator for the Space Weather Prediction Center, at a news briefing Wednesday.

    A series of the most intense type of solar flares, known as X-class flares, have released from the sun this week. The flares also coincided with coronal mass ejections on Tuesday.

    Coronal mass ejections are large clouds of ionized gas called plasma and magnetic fields that erupt from the sun’s outer atmosphere. When these outbursts are directed at Earth, they can cause geomagnetic storms, or major disturbances of Earth’s magnetic field.

    “Geomagnetic storms can impact infrastructure in near-Earth orbit and on Earth’s surface,” according to the Space Weather Prediction Center.

    As a result, the center has notified the Federal Emergency Management Agency, the North American power grid and satellite operators to prepare for disruptions, especially given the amount of preparations and expected relief efforts for Hurricane Milton, Dahl said.

    Historically, G4 storms are common during a solar cycle, but G5, or extreme geomagnetic storms such the one that occurred on May 10, are incredibly rare, Dahl said. This new storm has a 25% chance of becoming a G5, he said.

  12. SamuelCic表示:

    https://amoxil.llc/# amoxicillin 500mg buy online uk

  13. She was born in DeQueen, Arkansas, on January 27, 1908, to Laura Alice Murrey Griffin and Charlie Melvin Griffin.

  14. Michaelgax表示:

    generic zithromax 500mg india zithromax for sale zithromax 250 mg pill

  15. Consider using set off locks or cable locks when firearms aren’t in use to forestall accidental discharges.

  16. RichardFoumn表示:

    Thai farmer forced to kill more than 100 endangered crocodiles after a typhoon damaged their enclosure
    kraken darknet onion
    A Thai crocodile farmer who goes by the nickname “Crocodile X” said he killed more than 100 critically endangered reptiles to prevent them from escaping after a typhoon damaged their enclosure.

    Natthapak Khumkad, 37, who runs a crocodile farm in Lamphun, northern Thailand, said he scrambled to find his Siamese crocodiles a new home when he noticed a wall securing their enclosure was at risk of collapsing. But nowhere was large or secure enough to hold the crocodiles, some of which were up to 4 meters (13 feet) long.

    To stop the crocodiles from getting loose into the local community, Natthapak said, he put 125 of them down on September 22.

    “I had to make the most difficult decision of my life to kill them all,” he told CNN. “My family and I discussed if the wall collapsed the damage to people’s lives would be far bigger than we can control. It would involve people’s lives and public safety.”
    Typhoon Yagi, Asia’s most powerful storm this year, swept across southern China and Southeast Asia this month, leaving a trail of destruction with its intense rainfall and powerful winds. Downpours inundated Thailand’s north, submerging homes and riverside villages, killing at least nine people.

    Storms like Yagi are “getting stronger due to climate change, primarily because warmer ocean waters provide more energy to fuel the storms, leading to increased wind speeds and heavier rainfall,” said Benjamin Horton, director of the Earth Observatory of Singapore.

    Natural disasters, including typhoons, pose a range of threats to wildlife, according to the International Fund for Animal Welfare. Flooding can leave animals stranded, in danger of drowning, or separated from their owners or families.

    Rain and strong winds can also severely damage habitats and animal shelters. In 2022, Hurricane Ian hit Florida and destroyed the Little Bear Sanctuary in Punta Gorda, leaving 200 animals, including cows, horses, donkeys, pigs and birds without shelter.

    The risk of natural disasters to animals is only increasing as human-caused climate change makes extreme weather events more frequent and volatile.

  17. Rogeliobib表示:

    Найти специалиста по независимой экспертизе и оценке!

    Сайт-агрегатор компаний и услуг в сфере независимой экспертизы и оценки.
    Мы создали этот проект, чтобы помочь вам найти надежных и опытных профессионалов
    для решения ваших задач.

    Главная цель — сделать процесс поиска специалистов по независимой экспертизе
    и оценке максимально простым и эффективным. Мы стремимся предоставить вам
    доступ к компаниям, которые гарантируют высокое качество услуг.
    С нами вы сможете быстро найти нужного эксперта и сравнить различные предложения.

    На нашем сайте собраны карточки компаний, каждая из которых содержит подробную
    информацию о предоставляемых услугах. Посетители могут фильтровать предложения
    по различным критериям:

    Локация
    Направление экспертизы
    Стоимость услуг
    Отзывы клиентов

    Наш сайт Специалисты по независимой экспертизе и оценке.

  18. Explore decor rooms library instagram A victorian fireplace grew to become the constructing block for an atlanta library.

  19. NicolasLoole表示:

    http://amoxil.llc/# amoxicillin generic

  20. L.L. Shelly, Lockesburg, Mrs.

  21. We also have a “shrimp only plate”.

  22. Nonetheless, if you’d like someone to kind out your entire journey for you, arranging all your trains, resorts and transfers, and to look after you if something impacts your arrangements, discuss to Railbookers.

  23. вывод из запоя капельница краснодар вывод из запоя капельница краснодар .

  24. This web page is really a walk-by means of for all of the information you needed about this and didn?t know who to ask. Glimpse right here, and you?ll undoubtedly uncover it.

  25. Stevenjaw表示:

    https://amoxil.llc/# amoxicillin 775 mg
    zithromax online

  26. Matthewweind表示:

    ivermectin 3mg tablet: cheapest stromectol – buy minocycline 50mg otc

  27. Michaelgax表示:

    cheap Rybelsus 14 mg Buy compounded semaglutide online rybelsus cost

發佈留言

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