POI讀取Excel文件

maven依賴:

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.15</version>
		</dependency>

代碼:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import net.sf.json.JSONObject;

public class PoiUtils {
	
	public static void main(String args[]) {
		poiExcel();
	}
	
	public static void poiExcel() {
		String filePath = "C:\\Users\\Administrator\\Desktop\\hehe.xls";
		try {
			List<Map> listMap = readExcel(filePath);
			/*
			 *list中存放當前excel中所有的sheet,每個sheet爲一個map
			 *
			 * 每個map:三個字段
			 *  file_Name   	:excel文件名
				sheet_Name		:sheet文名
				sheet_content 	:sheet內容
			 */
			for (int i = 0; i < listMap.size(); i++) {
				Map tempMap = listMap.get(i);
				String file_Name		= (String) tempMap.get("file_Name");
				String sheet_Name		= (String) tempMap.get("sheet_Name");
				String sheet_content	= (String) tempMap.get("sheet_content");
//				System.out.println(file_Name + "\t\t"+sheet_Name +"\t\t"+sheet_content);
				JSONObject json = new JSONObject();
				json.put("file_Name", file_Name);
				json.put("sheet_Name", sheet_Name);
				json.put("sheet_content", sheet_content);
				System.out.println(json);
			}
//			for (Map map : listMap) {
//				System.out.println(map);
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 讀取excel
	 * @param filePath
	 * @return List<Map>
	 * @throws Exception
	 */
	public static List<Map> readExcel(String filePath) throws Exception {
		File file = new File(filePath);
		if (!file.exists()) {
			return null;
		}
		String suffix = "";
		if (filePath.indexOf(".xlsx") != -1) {
			suffix = ".xlsx";
		} else if (filePath.indexOf(".xls") != -1) {
			suffix = ".xls";
		} else {
			return null;
		}

		// 返回值列
		List<Map> reaultList = new ArrayList<Map>();
		if (".xls".equals(suffix)) {
			reaultList = readExcel2003(filePath);
		} else if (".xlsx".equals(suffix)) {
			reaultList = readExcel2007(filePath);
		}

		return reaultList;
	}

	/**
	 * 讀取97-2003格式(即xls格式)
	 */
	public static List<Map> readExcel2003(String filePath) throws IOException {
		// 返回結果集
		List<Map> resurtListMap = new ArrayList<Map>();
		FileInputStream fis = null;

		File file = new File(filePath);
		String file_Name = file.getName();

		try {
			fis = new FileInputStream(filePath);
			HSSFWorkbook wookbook = new HSSFWorkbook(fis); // 創建對Excel工作簿文件的引用
			// 遍歷所有sheet
			for (int page = 0; page < wookbook.getNumberOfSheets(); page++) {
				Map<String, String> sheet_map = new HashMap<>();
				
				HSSFSheet sheet = wookbook.getSheetAt(page); // 在Excel文檔中,第page張工作表的缺省索引是0
				int rows = sheet.getPhysicalNumberOfRows(); // 獲取到Excel文件中的所有行數
				String sheet_Name = sheet.getSheetName();// sheet名稱,用於校驗模板是否正確
				String sheet_content = "";
				int cells = 0;// 當前sheet的行數
				// 遍歷sheet中所有的行
				HSSFRow firstRow = sheet.getRow(page);
				if (firstRow != null) {
					// 獲取到Excel文件中的所有的列
					cells = firstRow.getPhysicalNumberOfCells();
					for (int i = 0; i < rows; i++) {
						// 讀取左上端單元格
						HSSFRow row = sheet.getRow(i);
						// 行不爲空
						if (row != null) {
							boolean isValidRow = false;
							// 遍歷列
							for (int j = 0; j < cells; j++) {
								// 獲取到列的值
								try {
									HSSFCell cell = row.getCell(j);
									String cellValue = getCellValue(cell);
									if(cellValue == null)
									{
										cellValue = "";
									}
									sheet_content += cellValue+"\t";
									if (!isValidRow && cellValue != null
											&& cellValue.trim().length() > 0) {
										isValidRow = true;
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							sheet_content += "\n";
						}
					}
				}
				//封裝每個sheet入map
				sheet_map.put("file_Name", 		file_Name);
				sheet_map.put("sheet_Name", 	sheet_Name);
				sheet_map.put("sheet_content", 	sheet_content);
				resurtListMap.add(sheet_map);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			fis.close();
		}
		return resurtListMap;
	}


	/**
	 * 讀取2007格式(即xlsx)
	 */
	public static List<Map> readExcel2007(String filePath) throws IOException {
		// 返回結果集
		List<Map> resurtListMap = new ArrayList<Map>();
		FileInputStream fis = null;

		File file = new File(filePath);
		String file_Name = file.getName();

		try {
			fis = new FileInputStream(filePath);
			XSSFWorkbook wookbook = new XSSFWorkbook(fis); // 創建對Excel工作簿文件的引用
			// 遍歷所有sheet
			for (int page = 0; page < wookbook.getNumberOfSheets(); page++) {
				Map<String, String> sheet_map = new HashMap<>();
				
				XSSFSheet sheet = wookbook.getSheetAt(page); // 在Excel文檔中,第page張工作表的缺省索引是0
				int rows = sheet.getPhysicalNumberOfRows(); // 獲取到Excel文件中的所有行數
				String sheet_Name = sheet.getSheetName();// sheet名稱,用於校驗模板是否正確
				String sheet_content = "";
				int cells = 0;// 當前sheet的行數
				// 遍歷sheet中所有的行
				XSSFRow firstRow = sheet.getRow(page);
				if (firstRow != null) {
					// 獲取到Excel文件中的所有的列
					cells = firstRow.getPhysicalNumberOfCells();
					for (int i = 0; i < rows; i++) {
						// 讀取左上端單元格
						XSSFRow row = sheet.getRow(i);
						// 行不爲空
						if (row != null) {
							boolean isValidRow = false;
							// 遍歷列
							for (int j = 0; j < cells; j++) {
								// 獲取到列的值
								try {
									XSSFCell cell = row.getCell(j);
									String cellValue = getCellValue(cell);
									if(cellValue == null)
									{
										cellValue = "";
									}
									sheet_content += cellValue+"\t";
									if (!isValidRow && cellValue != null
											&& cellValue.trim().length() > 0) {
										isValidRow = true;
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							sheet_content += "\n";
						}
					}
				}
				//封裝每個sheet入map
				sheet_map.put("file_Name", 		file_Name);
				sheet_map.put("sheet_Name", 	sheet_Name);
				sheet_map.put("sheet_content", 	sheet_content);
				resurtListMap.add(sheet_map);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			fis.close();
		}
		return resurtListMap;
	}

	private static String getCellValue(HSSFCell cell) {
		DecimalFormat df = new DecimalFormat("#");
		String cellValue = null;
		if (cell == null)
			return null;
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell
						.getNumericCellValue()));
				break;
			}
			cellValue = df.format(cell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_STRING:
			cellValue = String.valueOf(cell.getStringCellValue());
			break;
		case HSSFCell.CELL_TYPE_FORMULA:
			cellValue = String.valueOf(cell.getCellFormula());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			cellValue = null;
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			cellValue = String.valueOf(cell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_ERROR:
			cellValue = String.valueOf(cell.getErrorCellValue());
			break;
		}
		if (cellValue != null && cellValue.trim().length() <= 0) {
			cellValue = null;
		}
		return cellValue;
	}

	private static String getCellValue(XSSFCell cell) {
		DecimalFormat df = new DecimalFormat("#");
		String cellValue = null;
		if (cell == null)
			return null;
		switch (cell.getCellType()) {
		case XSSFCell.CELL_TYPE_NUMERIC:
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell
						.getNumericCellValue()));
				break;
			}
			cellValue = df.format(cell.getNumericCellValue());
			break;
		case XSSFCell.CELL_TYPE_STRING:
			cellValue = String.valueOf(cell.getStringCellValue());
			break;
		case XSSFCell.CELL_TYPE_FORMULA:
			cellValue = String.valueOf(cell.getCellFormula());
			break;
		case XSSFCell.CELL_TYPE_BLANK:
			cellValue = null;
			break;
		case XSSFCell.CELL_TYPE_BOOLEAN:
			cellValue = String.valueOf(cell.getBooleanCellValue());
			break;
		case XSSFCell.CELL_TYPE_ERROR:
			cellValue = String.valueOf(cell.getErrorCellValue());
			break;
		}
		if (cellValue != null && cellValue.trim().length() <= 0) {
			cellValue = null;
		}
		return cellValue;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章