使用POI读写Excel文件(兼容xls与xlsx版本)

调用示例:

//生成Excel文档
File excelFile = new File("D:\\temp.xls");

Map value1Map = new HashMap(); //第一行数据
value1Map.put("Name"   , "张三");
value1Map.put("Gender" , "男");

Map value2Map = new HashMap(); //第二行数据
value2Map.put("Name"   , "李四");
value2Map.put("Gender" , "女");

List sheetList = new ArrayList(); //Sheet页列表
sheetList.add(value1Map);
sheetList.add(value2Map);

List excelList = new ArrayList(); //数据列表
excelList.add(sheetList);

List columnKeyList = new ArrayList(); //行数据键列表
columnKeyList.add("Name");
columnKeyList.add("Gender");

List sheetColumnKeyList = new ArrayList(); //Sheet行数据键列表
sheetColumnKeyList.add(columnKeyList);

List titleNameList = new ArrayList(); //输出文件字段名列表
titleNameList.add("姓名");
titleNameList.add("性别");

List sheetTitleNameList = new ArrayList(); //Sheet输出文件字段名列表
sheetTitleNameList.add(titleNameList);

ExcelFileUtil.writeToExcelFile(excelList , sheetColumnKeyList , sheetTitleNameList , excelFile.getCanonicalPath());

//读取Excel文档内容
System.out.println(ExcelFileUtil.readFromExcelFile(excelFile));

//读取Excel文档中所有内容,以字符串形式返回
System.out.println(ExcelFileUtil.extractText(excelFile , "," , "\n" , "\n\n"));


工具类源码:

/**
 * BaseExcelFileUtil.java
 * Copyright ® 2017 窦海宁
 * All right reserved
 */

package org.aiyu.core.common.util.file.office;

import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.aiyu.core.common.util.CollectionUtil;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * <p>Excel文件工具基类
 * 
 * <p>通用的Excel文件工具基类,可用于从Excel文档中抽取或写入信息
 * 
 * @author  窦海宁, [email protected]
 * @since   AiyuCommonCore-1.0
 * @version AiyuCommonCore-1.0
 */
public abstract class BaseExcelFileUtil {

	final protected static DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM , DateFormat.MEDIUM);

	/**
	 * <p>读取Excel文件中的工作薄
	 * 
	 * @param  workbook        工作表对象
	 * @param  startSheetIndex 起始Sheet表索引,第一个Sheet从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endSheetIndex   结束Sheet表索引,如传入值大于总Sheet表数,在此方法中会被初始化为总Sheet表数 - 1
	 * @param  startRowIndex   起始行索引,第一行从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endRowIndex     结束行索引,如传入值大于总行数,在此方法中会被初始化为总行数 - 1
	 * @param  titleRowIndex   标题行索引
	 * 
	 * @return 读取出的工作薄列表
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static List readWorkbook(Workbook workbook , int startSheetIndex , int endSheetIndex , int startRowIndex , int endRowIndex , int titleRowIndex) throws IOException {

		//检查并确保Sheet表起始索引为正常值
		if (startSheetIndex < 0) {

			startSheetIndex = 0;
		}

		if (endSheetIndex < 0) {

			endSheetIndex = workbook.getNumberOfSheets() - 1;
		} else {

			endSheetIndex = endSheetIndex > workbook.getNumberOfSheets() - 1 ? workbook.getNumberOfSheets() - 1 : endSheetIndex;
		}

		//读取Sheet表
		List sheetValueList = null;
		if (workbook != null) {

			sheetValueList = new ArrayList();
			for (int i = startSheetIndex ; i <= endSheetIndex ; i++) {

				sheetValueList.add(BaseExcelFileUtil.readSheet(workbook.getSheetAt(i) , startRowIndex , endRowIndex , titleRowIndex));
			}
		}
		return sheetValueList;
	}

	/**
	 * <p>读取Sheet表中的数据
	 * 
	 * @param  sheet         Sheet表对象
	 * @param  startRowIndex 起始行索引,第一行从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endRowIndex   结束行索引,如传入值大于总行数,在此方法中会被初始化为总行数 - 1
	 * @param  titleRowIndex 标题行索引
	 * 
	 * @return 读取出的行列表
	 * 
	 * @modify 窦海宁, 2017-02-06
	 */
	protected static List readSheet(Sheet sheet , int startRowIndex , int endRowIndex , int titleRowIndex) {

		//检查并确保行起始索引为正常值
		if (startRowIndex < 0) {

			startRowIndex = 0;
		}

		if (endRowIndex < 0) {

			endRowIndex = sheet.getLastRowNum();
		} else {

			endRowIndex = endRowIndex > sheet.getLastRowNum() ? endRowIndex : sheet.getLastRowNum();
		}

		//读取行
		List rowValueList = null;
		if (sheet != null) {

			//读取标题行
			List titleKeyList = BaseExcelFileUtil.readTitleKeyList(sheet , titleRowIndex);

			rowValueList = new ArrayList();
			for (int i = startRowIndex ; i <= endRowIndex ; i++) {

				Map rowMap = BaseExcelFileUtil.readRow(sheet.getRow(i) , titleKeyList);
				if (CollectionUtil.isNotEmpty(rowMap)) {

					rowValueList.add(rowMap);
				}
			}
		}
		return rowValueList;
	}

	/**
	 * <p>读取指定的Sheet表中的键名
	 * <p>如在前端使用,建议Excel文件中使用中文名称,便于直接显示
	 * <p>如在后端使用,建议Excel文件中使用英文名称,并与数据库中字段名称一一对应,便于将读取出的数据对象直接应用于数据库
	 * 
	 * @param  sheet         Sheet表对象
	 * @param  titleRowIndex 标题行索引
	 * 
	 * @return 读取出的标题列表
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static List readTitleKeyList(Sheet sheet , int titleRowIndex) {

		List titleKeyList = null;
		if (sheet != null) {

			Row row = sheet.getRow(titleRowIndex);
			if (row != null) {

				titleKeyList = new ArrayList();
				for (int i = 0 ; i < row.getLastCellNum() ; i++) {

					Object titleKey = BaseExcelFileUtil.readCell(row.getCell(i));
					if (titleKey != null) {

						titleKeyList.add(titleKey);
					}
				}
			}
		}
		return titleKeyList;
	}

	/**
	 * <p>读取指定的Sheet表中的一行数据
	 * 
	 * @param  row          Sheet表中的行对象
	 * @param  titleKeyList 标题键列表
	 * 
	 * @return 读取出的Cell值列表
	 * 
	 * @modify 窦海宁, 2017-02-06
	 */
	protected static Map readRow(Row row , List titleKeyList) {

		Map cellValueMap = null;
		if (row != null) {

			cellValueMap = new LinkedHashMap();
			for (int i = 0 ; i < titleKeyList.size() ; i++) {

				if (row.getCell(i) != null) {

					cellValueMap.put(titleKeyList.get(i) , BaseExcelFileUtil.readCell(row.getCell(i)));
				}
			}
		}
		return cellValueMap;
	}


	/**
	 * <p>读取指定的单元格的数据
	 * 
	 * @param  cell Sheet表中的单元格对象
	 * 
	 * @return 读取出的Cell值
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static Object readCell(Cell cell) {

		Object cellValue = null;

		if (cell != null) {

			CellType cellType = cell.getCellTypeEnum();
			if (cellType == CellType.BLANK) {
				
			} else if (cellType == CellType.BOOLEAN) {

				cellValue = Boolean.valueOf(cell.getBooleanCellValue());
			} else if (cellType == CellType.FORMULA) {

				cellValue = cell.getCellFormula();
			} else if (cellType == CellType.NUMERIC) {

				if (HSSFDateUtil.isCellDateFormatted(cell)) {

					cellValue = cell.getDateCellValue();
				} else {

					cellValue = Double.valueOf((cell.getNumericCellValue()));
				}
			} else if (cellType == CellType.STRING) {

				// 取得当前的Cell字符串
				cellValue = cell.getRichStringCellValue().getString();
			} else if (cellType == CellType.ERROR) {

				//错误处理
			}
		}
		return cellValue;
	}

	/**
	 * <p>读取指定的单元格中的文本数据
	 * 
	 * @param  cellValue 单元格数据
	 * 
	 * @return 读取出的文本
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static String readCellAsText(Object cellValue) {

		String returnValue = null;
		if (cellValue instanceof String) {

			returnValue = (String) cellValue;
		} else if (cellValue instanceof Boolean) {

			returnValue = ((Boolean) cellValue).toString();
		} else if (cellValue instanceof Double) {

			returnValue = ((Double) cellValue).toString();
		} else if (cellValue instanceof Date) {

			if (BaseExcelFileUtil.dateFormat == null) {

				returnValue = ((Date) cellValue).toString();
			} else {

				returnValue = BaseExcelFileUtil.dateFormat.format((Date) cellValue);
			}
		}
		return returnValue;
	}

}
  Excel2003版本工具类:  
/**
 * Excel2003FileUtil.java
 * Copyright &reg; 2010 窦海宁
 * All right reserved
 */

package org.aiyu.core.common.util.file.office;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.aiyu.core.common.util.CollectionUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
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.ss.usermodel.CellType;

/**
 * <p>Excel2003版文件工具类
 * 
 * <p>通用的Excel2003版文件工具类,可用于从Excel文档中抽取或写入信息
 * 
 *<br> ExcelList(数据列表结构):
 *<br> ExcelList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_2_Map
 *<br>     |      |-- Row_3_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_2_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Row_N_Map
 *<p>
 *<br> columnKeyList(数据列键列表结构)
 *<br> columnKeyList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_2
 *<br>     |      |-- Column_Key_3
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_2
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Column_Key_N
 *<p>
 *<br> titleNameList(标题列标题列表数据结构)
 *<br> titleNameList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_2
 *<br>     |      |-- Title_Name_3
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_2
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Title_Name_N
 * 
 * @author  窦海宁, [email protected]
 * @since   AiyuCommonCore-1.0
 * @version AiyuCommonCore-1.0
 */
public abstract class Excel2003FileUtil extends BaseExcelFileUtil {

	/**
	 * <p>从Excel文档中提取文本信息
	 * 
	 * @param  excelFile      Excel文件
	 * @param  cellSeparator  Cell分隔符
	 * @param  rowSeparator   Row分隔符
	 * @param  sheetSeparator Sheet分隔符
	 * 
	 * @return 提取后的文本信息
	 * 
	 * @modify 窦海宁, 2013-07-03
	 */
	protected static String extractText(File excelFile , String cellSeparator , String rowSeparator , String sheetSeparator) {

		StringBuffer returnValue = new StringBuffer();
		if (excelFile != null && cellSeparator != null && rowSeparator != null && sheetSeparator != null) {

			if (excelFile.isFile()) {

				Iterator sheetIterator = Excel2003FileUtil.readFromExcelFile(excelFile).iterator();
				//遍历Sheet
				while (sheetIterator.hasNext()) {

					Iterator rowIterator = ((List) sheetIterator.next()).iterator();
					//遍历Row
					while (rowIterator.hasNext()) {

						Iterator cellIterator = ((Map) rowIterator.next()).values().iterator();
						//遍历Cell
						while (cellIterator.hasNext()) {

							String cellValue = Excel2003FileUtil.readCellAsText(cellIterator.next());
							if (cellValue != null) {

								returnValue.append(cellValue);
								//添加Cell分隔符
								if (cellIterator.hasNext()) {

									returnValue.append(cellSeparator);
								}
							}
						}
						//添加Row分隔符
						if (rowIterator.hasNext()) {

							returnValue.append(rowSeparator);
						}
					}
					//添加Sheet分隔符
					if (sheetIterator.hasNext()) {

						returnValue.append(sheetSeparator);
					}
				}
			}
		}
		return StringUtils.trimToNull(returnValue.toString());
	}

	/**
	 * <p>读取Excel文档所有数据,标题行默认为第一行
	 * 
	 * @param  excelFile Excel文件
	 * 
	 * @return Excel文档数据
	 * 
	 * @modify 窦海宁, 2010-11-19
	 */
	protected static List readFromExcelFile(File excelFile) {

		return Excel2003FileUtil.readFromExcelFile(excelFile , 0 , -1 , 1 , -1 , 0);
	}

	/**
	 * <p>读取Excel文档数据
	 * 
	 * @param  excelFile       Excel文件
	 * @param  startSheetIndex 起始Sheet表索引,第一个Sheet从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endSheetIndex   结束Sheet表索引,如传入值大于总Sheet表数,在此方法中会被初始化为总Sheet表数 - 1
	 * @param  startRowIndex   起始行索引,第一行从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endRowIndex     结束行索引,如传入值大于总行数,在此方法中会被初始化为总行数 - 1
	 * @param  titleRowIndex   标题行索引
	 * 
	 * @return Excel文档数据
	 * 
	 * @modify 窦海宁, 2013-07-03
	 */
	protected static List readFromExcelFile(File excelFile , int startSheetIndex , int endSheetIndex , int startRowIndex , int endRowIndex , int titleRowIndex) {

		List excelList = null;
		if (excelFile != null) {

			if (excelFile.isFile()) {

				FileInputStream fileInputStream = null;
				try {

					fileInputStream = new FileInputStream(excelFile);
					excelList = Excel2003FileUtil.readWorkbook(new HSSFWorkbook(fileInputStream) , startSheetIndex , endSheetIndex , startRowIndex , endRowIndex , titleRowIndex);
				} catch (Exception ex) {

					ex.printStackTrace();
				} finally {

					IOUtils.closeQuietly(fileInputStream);
				}
			}
		}
		return excelList;
	}

	/**
	 * <p>写入数据到Excel文档
	 * 
	 * @param  excelList     数据列表,由映射行数据的Map组成,Excel列数据的写顺序由keyList中的数据键顺序指定
	 * @param  columnKeyList 数据列标题列表
	 * @param  titleNameList 标题列表
	 * @param  saveFilePath  Excel文件保存路径
	 * 
	 * @return 目标Excel文件路径,创建失败返回null
	 * 
	 * @modify 窦海宁, 2015-05-26
	 */
	protected static boolean writeToExcelFile(List excelList , List columnKeyList , List titleNameList , String saveFilePath) {

		return Excel2003FileUtil.writeToExcelFile(excelList , null , columnKeyList , titleNameList , saveFilePath);
	}

	/**
	 * <p>写入数据到Excel文档
	 * 
	 * @param  excelList          数据列表,由映射行数据的Map组成,Excel列数据的写顺序由keyList中的数据键顺序指定
	 * @param  sheetTitleList     数据页标题列表(可为null)
	 * @param  sheetColumnKeyList 数据列键列表
	 * @param  sheetTitleNameList 数据列标题列表
	 * @param  saveFilePath       Excel文件保存路径
	 * 
	 * @return 目标Excel文件路径,创建失败返回null
	 * 
	 * @modify 窦海宁, 2017-03-20
	 */
	protected static boolean writeToExcelFile(List excelList , List sheetTitleList , List sheetColumnKeyList , List sheetTitleNameList , String saveFilePath) {

		boolean result = false;

		if (sheetColumnKeyList!= null && !sheetColumnKeyList.isEmpty()) {

			HSSFWorkbook workbook = new HSSFWorkbook();
			for (int i = 0 ; i < excelList.size() ; i++) {

				//处理Sheet页

				List sheetList     = (List) excelList.get(i);
				List columnKeyList = (List) sheetColumnKeyList.get(i);
				List titleNameList = (List) sheetTitleNameList.get(i);

				HSSFSheet sheet = null;
				if (CollectionUtil.isNotEmpty(sheetTitleList)) {

					sheet = workbook.createSheet((String) sheetTitleList.get(i));
				} else {

					sheet = workbook.createSheet();
				}

				HSSFRow row = null;
				int startRowIndex = 0;

				//生成标题行
				if (CollectionUtil.isNotEmpty(titleNameList)) {

					row = sheet.createRow(startRowIndex++);
					for (int j = 0 ; j < titleNameList.size() ; j++) {

						Object   value = titleNameList.get(j);
						HSSFCell cell  = row.createCell(j);
						cell.setCellType(CellType.STRING);
						cell.setCellValue(value == null ? null : value.toString());
					}
				}

				//生成数据行
				if (sheetList != null) {

					for (int j = 0 ; j < sheetList.size() ; j++) {

						Map rowMap = (Map) sheetList.get(j);

						row = sheet.createRow(j + startRowIndex);
						for (int k = 0 ; k < columnKeyList.size() ; k++) {

							Object   value = rowMap.get(columnKeyList.get(k));
							HSSFCell cell  = row.createCell(k);
							cell.setCellType(CellType.STRING);
							cell.setCellValue(value == null ? null : value.toString());
						}
					}
				}
			}

			//写入文档
			FileOutputStream outputStream = null;
			try {

				outputStream = new FileOutputStream(saveFilePath);
				workbook.write(outputStream);
				outputStream.flush();
				outputStream.close();

				result = true;
			} catch (Exception ex) {

				ex.printStackTrace();
			} finally {

				IOUtils.closeQuietly(outputStream);
			}
		}

		return result;
	}

}
  Excel2007版本工具类:  
/**
 * Excel2007FileUtil.java
 * Copyright &reg; 2017 窦海宁
 * All right reserved
 */

package org.aiyu.core.common.util.file.office;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.aiyu.core.common.util.CollectionUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
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;

/**
 * <p>Excel2007版文件工具类
 * 
 * <p>通用的Excel2007版文件工具类,可用于从Excel文档中抽取或写入信息
 * 
 *<br> ExcelList(数据列表结构):
 *<br> ExcelList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_2_Map
 *<br>     |      |-- Row_3_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_2_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Row_N_Map
 *<p>
 *<br> columnKeyList(数据列键列表结构)
 *<br> columnKeyList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_2
 *<br>     |      |-- Column_Key_3
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_2
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Column_Key_N
 *<p>
 *<br> titleNameList(标题列标题列表数据结构)
 *<br> titleNameList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_2
 *<br>     |      |-- Title_Name_3
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_2
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Title_Name_N
 * 
 * @author  窦海宁, [email protected]
 * @since   AiyuCommonCore-1.0
 * @version AiyuCommonCore-1.0
 */
public abstract class Excel2007FileUtil extends BaseExcelFileUtil {

	/**
	 * <p>从Excel文档中提取文本信息
	 * 
	 * @param  excelFile      Excel文件
	 * @param  cellSeparator  Cell分隔符
	 * @param  rowSeparator   Row分隔符
	 * @param  sheetSeparator Sheet分隔符
	 * 
	 * @return 提取后的文本信息
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static String extractText(File excelFile , String cellSeparator , String rowSeparator , String sheetSeparator) {

		StringBuffer returnValue = new StringBuffer();
		if (excelFile != null && cellSeparator != null && rowSeparator != null && sheetSeparator != null) {

			if (excelFile.isFile()) {

				Iterator sheetIterator = Excel2007FileUtil.readFromExcelFile(excelFile).iterator();
				//遍历Sheet
				while (sheetIterator.hasNext()) {

					Iterator rowIterator = ((List) sheetIterator.next()).iterator();
					//遍历Row
					while (rowIterator.hasNext()) {

						Iterator cellIterator = ((Map) rowIterator.next()).values().iterator();
						//遍历Cell
						while (cellIterator.hasNext()) {

							String cellValue = Excel2007FileUtil.readCellAsText(cellIterator.next());
							if (cellValue != null) {

								returnValue.append(cellValue);
								//添加Cell分隔符
								if (cellIterator.hasNext()) {

									returnValue.append(cellSeparator);
								}
							}
						}
						//添加Row分隔符
						if (rowIterator.hasNext()) {

							returnValue.append(rowSeparator);
						}
					}
					//添加Sheet分隔符
					if (sheetIterator.hasNext()) {

						returnValue.append(sheetSeparator);
					}
				}
			}
		}
		return StringUtils.trimToNull(returnValue.toString());
	}

	/**
	 * <p>读取Excel文档所有数据,标题行默认为第一行
	 * 
	 * @param  excelFile Excel文件
	 * 
	 * @return Excel文档数据
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static List readFromExcelFile(File excelFile) {

		return Excel2007FileUtil.readFromExcelFile(excelFile , 0 , -1 , 1 , -1 , 0);
	}

	/**
	 * <p>读取Excel文档数据
	 * 
	 * @param  excelFile       Excel文件
	 * @param  startSheetIndex 起始Sheet表索引,第一个Sheet从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endSheetIndex   结束Sheet表索引,如传入值大于总Sheet表数,在此方法中会被初始化为总Sheet表数 - 1
	 * @param  startRowIndex   起始行索引,第一行从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endRowIndex     结束行索引,如传入值大于总行数,在此方法中会被初始化为总行数 - 1
	 * @param  titleRowIndex   标题行索引
	 * 
	 * @return Excel文档数据
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static List readFromExcelFile(File excelFile , int startSheetIndex , int endSheetIndex , int startRowIndex , int endRowIndex , int titleRowIndex) {

		List excelList = null;
		if (excelFile != null) {

			if (excelFile.isFile()) {

				FileInputStream fileInputStream = null;
				try {

					fileInputStream = new FileInputStream(excelFile);
					excelList = Excel2007FileUtil.readWorkbook(new XSSFWorkbook(fileInputStream) , startSheetIndex , endSheetIndex , startRowIndex , endRowIndex , titleRowIndex);
				} catch (Exception ex) {

					ex.printStackTrace();
				} finally {

					IOUtils.closeQuietly(fileInputStream);
				}
			}
		}
		return excelList;
	}

	/**
	 * <p>写入数据到Excel文档
	 * 
	 * @param  excelList     数据列表,由映射行数据的Map组成,Excel列数据的写顺序由keyList中的数据键顺序指定
	 * @param  columnKeyList 数据列标题列表
	 * @param  titleNameList 标题列表
	 * @param  saveFilePath  Excel文件保存路径
	 * 
	 * @return 目标Excel文件路径,创建失败返回null
	 * 
	 * @modify 窦海宁, 2017-01-18
	 */
	protected static boolean writeToExcelFile(List excelList , List columnKeyList , List titleNameList , String saveFilePath) {

		return Excel2007FileUtil.writeToExcelFile(excelList , null , columnKeyList , titleNameList , saveFilePath);
	}

	/**
	 * <p>写入数据到Excel文档
	 * 
	 * @param  excelList          数据列表,由映射行数据的Map组成,Excel列数据的写顺序由keyList中的数据键顺序指定
	 * @param  sheetTitleList     数据页标题列表(可为null)
	 * @param  sheetColumnKeyList 数据列键列表
	 * @param  sheetTitleNameList 数据列标题列表
	 * @param  saveFilePath       Excel文件保存路径
	 * 
	 * @return 目标Excel文件路径,创建失败返回null
	 * 
	 * @modify 窦海宁, 2017-03-20
	 */
	protected static boolean writeToExcelFile(List excelList , List sheetTitleList , List sheetColumnKeyList , List sheetTitleNameList , String saveFilePath) {

		boolean result = false;

		if (sheetColumnKeyList!= null && !sheetColumnKeyList.isEmpty()) {

			XSSFWorkbook workbook = new XSSFWorkbook();
			for (int i = 0 ; i < excelList.size() ; i++) {

				//处理Sheet页

				List sheetList     = (List) excelList.get(i);
				List columnKeyList = (List) sheetColumnKeyList.get(i);
				List titleNameList = (List) sheetTitleNameList.get(i);

				XSSFSheet sheet = null;
				if (CollectionUtil.isNotEmpty(sheetTitleList)) {

					sheet = workbook.createSheet((String) sheetTitleList.get(i));
				} else {

					sheet = workbook.createSheet();
				}

				XSSFRow row = null;
				int startRowIndex = 0;

				//生成标题行
				if (CollectionUtil.isNotEmpty(titleNameList)) {

					row = sheet.createRow(startRowIndex++);
					for (int j = 0 ; j < titleNameList.size() ; j++) {

						Object   value = titleNameList.get(j);
						XSSFCell cell  = row.createCell(j);
						cell.setCellType(CellType.STRING);
						cell.setCellValue(value == null ? null : value.toString());
					}
				}

				//生成数据行
				if (sheetList != null) {

					for (int j = 0 ; j < sheetList.size() ; j++) {

						Map rowMap = (Map) sheetList.get(j);

						row = sheet.createRow(j + startRowIndex);
						for (int k = 0 ; k < columnKeyList.size() ; k++) {

							Object   value = rowMap.get(columnKeyList.get(k));
							XSSFCell cell  = row.createCell(k);
							cell.setCellType(CellType.STRING);
							cell.setCellValue(value == null ? null : value.toString());
						}
					}
				}
			}

			//写入文档
			FileOutputStream outputStream = null;
			try {

				outputStream = new FileOutputStream(saveFilePath);
				workbook.write(outputStream);
				outputStream.flush();
				outputStream.close();

				result = true;
			} catch (Exception ex) {

				ex.printStackTrace();
			} finally {

				IOUtils.closeQuietly(outputStream);
			}
		}

		return result;
	}

}
  统一调用工具类:  
/**
 * ExcelFileUtil.java
 * Copyright &reg; 2017 窦海宁
 * All right reserved
 */

package org.aiyu.core.common.util.file.office;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * <p>Excel文件工具类
 * 
 * <p>通用的Excel文件工具类,可用于从Excel文档中抽取或写入信息
 * 
 *<br> ExcelList(数据列表结构):
 *<br> ExcelList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_2_Map
 *<br>     |      |-- Row_3_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Row_1_Map
 *<br>     |      |-- Row_2_Map
 *<br>     |      |-- Row_N_Map
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Row_N_Map
 *<p>
 *<br> columnKeyList(数据列键列表结构)
 *<br> columnKeyList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_2
 *<br>     |      |-- Column_Key_3
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Column_Key_1
 *<br>     |      |-- Column_Key_2
 *<br>     |      |-- Column_Key_N
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Column_Key_N
 *<p>
 *<br> titleNameList(标题列标题列表数据结构)
 *<br> titleNameList
 *<br>     |-- Sheet_1_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_2
 *<br>     |      |-- Title_Name_3
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_2_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_3_List
 *<br>     |      |-- Title_Name_1
 *<br>     |      |-- Title_Name_2
 *<br>     |      |-- Title_Name_N
 *<br>     |-- Sheet_N_List
 *<br>     |      |-- Title_Name_N
 * 
 * @author  窦海宁, [email protected]
 * @since   AiyuCommonCore-1.0
 * @version AiyuCommonCore-1.0
 */
public abstract class ExcelFileUtil extends BaseExcelFileUtil {

	/**
	 * <p>从Excel文档中提取文本信息
	 * 
	 * @param  excelFile      Excel文件
	 * @param  cellSeparator  Cell分隔符
	 * @param  rowSeparator   Row分隔符
	 * @param  sheetSeparator Sheet分隔符
	 * 
	 * @return 提取后的文本信息
	 * 
	 * @modify 窦海宁, 2017-02-06
	 */
	public static String extractText(File excelFile , String cellSeparator , String rowSeparator , String sheetSeparator) {

		String resultText = null;

		if (excelFile != null && excelFile.exists()) {

			String extension = FilenameUtils.getExtension(excelFile.getName());
			if (StringUtils.equalsIgnoreCase("xls" , extension)) {

				//Office2003版文件处理
				resultText = Excel2003FileUtil.extractText(excelFile , cellSeparator , rowSeparator , sheetSeparator);
			} else if (StringUtils.equalsIgnoreCase("xlsx" , extension)) {

				//Office2007版文件处理
				resultText = Excel2007FileUtil.extractText(excelFile , cellSeparator , rowSeparator , sheetSeparator);
			} else {

				//文件类型有误
			}
		}

		return resultText;
	}

	/**
	 * <p>读取Excel文档所有数据,标题行默认为第一行
	 * 
	 * @param  excelFile Excel文件
	 * 
	 * @return Excel文档数据
	 * 
	 * @modify 窦海宁, 2017-02-06
	 */
	public static List readFromExcelFile(File excelFile) {

		return ExcelFileUtil.readFromExcelFile(excelFile , 0 , -1 , 1 , -1 , 0);
	}

	/**
	 * <p>读取Excel文档数据
	 * 
	 * @param  excelFile       Excel文件
	 * @param  startSheetIndex 起始Sheet表索引,第一个Sheet从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endSheetIndex   结束Sheet表索引,如传入值大于总Sheet表数,在此方法中会被初始化为总Sheet表数 - 1
	 * @param  startRowIndex   起始行索引,第一行从0开始编号,如传入值小于0,在此方法中会被初始化为0
	 * @param  endRowIndex     结束行索引,如传入值大于总行数,在此方法中会被初始化为总行数 - 1
	 * @param  titleRowIndex   标题行索引
	 * 
	 * @return Excel文档数据
	 * 
	 * @modify 窦海宁, 2017-02-06
	 */
	public static List readFromExcelFile(File excelFile , int startSheetIndex , int endSheetIndex , int startRowIndex , int endRowIndex , int titleRowIndex) {

		List excelList = null;

		if (excelFile != null && excelFile.exists()) {

			String extension = FilenameUtils.getExtension(excelFile.getName());
			if (StringUtils.equalsIgnoreCase("xls" , extension)) {

				//Office2003版文件处理
				excelList = Excel2003FileUtil.readFromExcelFile(excelFile , startSheetIndex , endSheetIndex , startRowIndex , endRowIndex , titleRowIndex);
			} else if (StringUtils.equalsIgnoreCase("xlsx" , extension)) {

				//Office2007版文件处理
				excelList = Excel2007FileUtil.readFromExcelFile(excelFile , startSheetIndex , endSheetIndex , startRowIndex , endRowIndex , titleRowIndex);
			} else {

				//文件类型有误
			}
		}

		return excelList;
	}

	/**
	 * <p>写入数据到Excel文档
	 * 
	 * @param  excelList          数据列表,由映射行数据的Map组成,Excel列数据的写顺序由keyList中的数据键顺序指定
	 * @param  sheetColumnKeyList 数据列标题列表
	 * @param  sheetTitleNameList 标题列表
	 * @param  saveFilePath       Excel文件保存路径
	 * 
	 * @return 目标Excel文件路径,创建失败返回null
	 * 
	 * @modify 窦海宁, 2017-02-06
	 */
	public static boolean writeToExcelFile(List excelList , List sheetColumnKeyList , List sheetTitleNameList , String saveFilePath) {

		return ExcelFileUtil.writeToExcelFile(excelList , null , sheetColumnKeyList , sheetTitleNameList , saveFilePath);
	}

	/**
	 * <p>写入数据到Excel文档
	 * 
	 * @param  excelList          数据列表,由映射行数据的Map组成,Excel列数据的写顺序由keyList中的数据键顺序指定
	 * @param  sheetTitleList     数据页标题列表(可为null)
	 * @param  sheetColumnKeyList 数据列键列表
	 * @param  sheetTitleNameList 数据列标题列表
	 * @param  saveFilePath       Excel文件保存路径
	 * 
	 * @return 目标Excel文件路径,创建失败返回null
	 * 
	 * @modify 窦海宁, 2017-02-06
	 */
	public static boolean writeToExcelFile(List excelList , List sheetTitleList , List sheetColumnKeyList , List sheetTitleNameList , String saveFilePath) {

		boolean result = false;

		if (StringUtils.isNotBlank(saveFilePath)) {

			String extension = FilenameUtils.getExtension(saveFilePath);
			if (StringUtils.equalsIgnoreCase("xls" , extension)) {

				//Office2003版文件处理
				result = Excel2003FileUtil.writeToExcelFile(excelList , sheetTitleList , sheetColumnKeyList , sheetTitleNameList , saveFilePath);
			} else if (StringUtils.equalsIgnoreCase("xlsx" , extension)) {

				//Office2007版文件处理
				result = Excel2007FileUtil.writeToExcelFile(excelList , sheetTitleList , sheetColumnKeyList , sheetTitleNameList , saveFilePath);
			} else {

				//文件类型有误
			}
		}

		return result;
	}

}
  统一调用工具类通过文件扩展名(XLS与XLSX,不区分大小写)判断文件版本,暂时没有想到更好的办法;本工具类使用POI_3.15实现,无须目标机器安装OFFICE软件也可进行文件读写。

猜你喜欢

转载自chong0660.iteye.com/blog/1923204