天天看點

java 導入Excel 檔案,相容Excel 2003(字尾名:xls)及 2007(字尾名:xlsx)的檔案,同時還支援csv格式的檔案

1. 需要導入的jar包:

java 導入Excel 檔案,相容Excel 2003(字尾名:xls)及 2007(字尾名:xlsx)的檔案,同時還支援csv格式的檔案
java 導入Excel 檔案,相容Excel 2003(字尾名:xls)及 2007(字尾名:xlsx)的檔案,同時還支援csv格式的檔案

2.源代碼:

package com.kerwin.xls;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import au.com.bytecode.opencsv.CSVReader;

public class ImportExcelUtils {

	/**
	 * 讀取Excel的内容,第一維數組存儲的是多少行,二維數組存儲的每一行是多少列。<br>
	 * 相容Excel 2003(字尾名:xls)及 2007(字尾名:xlsx)的檔案,同時還支援讀取csv格式的檔案
	 * 
	 * @author Jiang <br>
	 *         2016年9月19日
	 * @param filePath
	 *            檔案完整路徑
	 * @param ignoreRows
	 *            讀取資料忽略的行數,例:行頭不需要讀入,忽略的行數為1,那麼将ignoreRows設為1即可
	 * @return
	 * @throws Exception
	 */
	public static String[][] importExcelFile(String filePath, int ignoreRows) throws IOException {

		/** 驗證檔案是否存在 */
		if (!validateFileExit(filePath)) {
			throw new IOException(filePath + "檔案不存在");
		}

		/** 如果是CSV格式調用ImportCsvFile方法,直接傳回結果 */
		if (isCsv(filePath)) {
			return importCsvFile(filePath, ignoreRows);
		}

		/** 驗證檔案是否合法 */
		if (!validateExcel(filePath)) {
			throw new RuntimeException("不是Excel格式的檔案");
		}

		List<String[]> result = new ArrayList<String[]>();
		Workbook workbook = null;
		InputStream inputStream = null;
		int rowSize = 0;

		try {

			File file = new File(filePath);
			inputStream = new FileInputStream(file);

			if (isExcel2003(filePath)) {
				workbook = new HSSFWorkbook(inputStream);
			} else {
				workbook = new XSSFWorkbook(inputStream);
			}

			for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
				Sheet sheet = workbook.getSheetAt(sheetIndex);
				for (int rowIndex = ignoreRows; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
					Row row = sheet.getRow(rowIndex);
					if (row == null) {
						continue;
					}
					int tempRowSize = row.getLastCellNum() + 1;
					if (tempRowSize > rowSize) {
						rowSize = tempRowSize;
					}
					String[] values = new String[rowSize];
					Arrays.fill(values, "");
					boolean hasValue = false;
					for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
						String value = "";
						Cell cell = row.getCell(columnIndex);
						if (cell != null) {
							switch (cell.getCellType()) {
							case HSSFCell.CELL_TYPE_STRING:
								value = cell.getStringCellValue();
								break;
							case HSSFCell.CELL_TYPE_NUMERIC:
								if (HSSFDateUtil.isCellDateFormatted(cell)) {
									Date date = cell.getDateCellValue();
									if (date != null) {
										value = new SimpleDateFormat("yyyy-MM-dd").format(date);
									} else {
										value = "";
									}
								} else {
									value = new DecimalFormat("0").format(cell.getNumericCellValue());
								}
								break;
							case HSSFCell.CELL_TYPE_FORMULA:
								// 導入時如果為公式生成的資料則無值
								if (!cell.getStringCellValue().equals("")) {
									value = cell.getStringCellValue();
								} else {
									value = cell.getNumericCellValue() + "";
								}
								break;
							case HSSFCell.CELL_TYPE_BLANK:
								break;
							case HSSFCell.CELL_TYPE_ERROR:
								value = "";
								break;
							case HSSFCell.CELL_TYPE_BOOLEAN:
								value = (cell.getBooleanCellValue() == true ? "Y" : "N");
								break;
							default:
								value = "";
							}
						}
						if (columnIndex == 0 && value.trim().equals("")) {
							break;
						}
						values[columnIndex] = rightTrim(value);
						hasValue = true;
					}

					if (hasValue) {
						result.add(values);
					}
				}
			}

			inputStream.close();
			workbook.close();
		} catch (IOException e) {
			throw e;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					inputStream = null;
					e.printStackTrace();
				}
			}
			if (workbook != null) {
				try {
					workbook.close();
				} catch (IOException e) {
					workbook = null;
					e.printStackTrace();
				}
			}
		}

		String[][] returnArray = new String[result.size()][rowSize];
		for (int i = 0; i < returnArray.length; i++) {
			returnArray[i] = (String[]) result.get(i);
		}
		return returnArray;
	}

	/**
	 * csv格式的檔案,第一維數組存儲的是多少行,二維數組存儲的每一行是多少列。<br>
	 * 
	 * @author Jiang <br>
	 *         2016年9月19日
	 * @param filePath
	 *            檔案完整路徑
	 * @param ignoreRows
	 *            讀取資料忽略的行數,例:行頭不需要讀入,忽略的行數為1,那麼将ignoreRows設為1即可
	 * @return
	 * @throws Exception
	 */
	public static String[][] importCsvFile(String filePath, int ignoreRows) throws IOException {
		/** 驗證檔案是否存在 */
		if (!validateFileExit(filePath)) {
			throw new IOException(filePath + "檔案不存在");
		}

		/** 驗證檔案是否合法 */
		if (!isCsv(filePath)) {
			throw new RuntimeException("不是csv格式的檔案");
		}
		InputStreamReader inputStream = null;
		CSVReader reader = null;
		List<String[]> result = new ArrayList<String[]>();
		int rowSize = 0;
		try {
			inputStream = new InputStreamReader(new FileInputStream(filePath), "GBK");
			reader = new CSVReader(inputStream);
			String[] nextRow = null;
			int i = 0;
			while ((nextRow = reader.readNext()) != null) {
				++i;
				if (i <= ignoreRows) {
					continue;
				}
				if (nextRow == null || nextRow.length <= 0) {
					continue;
				}
				int tempRowSize = nextRow.length;
				if (tempRowSize > rowSize) {
					rowSize = tempRowSize;
				}
				result.add(nextRow);
			}

			reader.close();
			inputStream.close();
		} catch (IOException e) {
			throw e;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					inputStream = null;
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					reader = null;
					e.printStackTrace();
				}
			}
		}

		String[][] returnArray = new String[result.size()][rowSize];
		for (int i = 0; i < returnArray.length; i++) {
			returnArray[i] = (String[]) result.get(i);
		}
		return returnArray;
	}

	/**
	 * 驗證excel檔案
	 * 
	 * @author Jiang <br>
	 *         2016年9月19日
	 * @param filePath
	 *             檔案完整路徑
	 * @return boolean
	 */
	public static boolean validateExcel(String filePath) {
		/** 檢查檔案名是否為空或者是否是Excel格式的檔案 */
		if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
			return false;
		}
		return true;
	}

	/**
	 * 檢查檔案是否存在,存在傳回true,不存在傳回false
	 * 
	 * @author Jiang <br>
	 *         2016年9月19日
	 * @param filePath
	 * @return
	 */
	public static boolean validateFileExit(String filePath) {
		File file = new File(filePath);
		if (file == null || !file.exists()) {
			return false;
		}
		return true;
	}

	/**
	 * 是否是2003的excel,傳回true是2003
	 * 
	 * @author Jiang <br>
	 *         2016年9月19日
	 * @param filePath
	 *            檔案完整路徑
	 * @return boolean
	 */
	public static boolean isExcel2003(String filePath) {
		return filePath.matches("^.+\\.(?i)(xls)$");
	}

	/**
	 * 是否是2007的excel,傳回true是2007
	 * 
	 * @author Jiang <br>
	 *         2016年9月19日
	 * @param filePath
	 *            檔案完整路徑
	 * @return boolean
	 */
	public static boolean isExcel2007(String filePath) {
		return filePath.matches("^.+\\.(?i)(xlsx)$");
	}

	/**
	 * 是否是csv格式的檔案,傳回true是csv格式
	 * 
	 * @author Jiang <br>
	 *         2016年9月19日
	 * @param filePath
	 *            檔案完整路徑
	 * @return boolean
	 */
	public static boolean isCsv(String filePath) {
		return filePath.matches("^.+\\.(?i)(csv)$");
	}

	/**
	 * 去掉字元串右邊的空格
	 * 
	 * @param str
	 *            要處理的字元串
	 * @return 處理後的字元串
	 */
	private static String rightTrim(String str) {
		if (str == null) {
			return "";
		}
		int length = str.length();
		for (int i = length - 1; i >= 0; i--) {
			if (str.charAt(i) != 0x20) {
				break;
			}
			length--;
		}
		return str.substring(0, length);
	}

	public static void main(String[] args) throws Exception {
		String[][] result = importExcelFile("D:/1.csv", 0);
		// String[][] result = importExcelFile("D:/2.xlsx", 1);
		// String[][] result = importExcelFile("D:/3.xls", 0);
		int rowLength = result.length;
		for (int i = 0; i < rowLength; i++) {
			for (int j = 0; j < result[i].length; j++) {
				System.out.print(result[i][j] + "\t\t");
			}
			System.out.println();
		}
	}

}
           

源碼及所需jar包下載下傳位址:http://download.csdn.net/detail/rain097790/9633883

繼續閱讀