项目中遇到需求:将Excel 文件中的读取出来 保存到数据库中。
这里讲解下,如何用POI 读取Excel 文件。 另:如何将数据存储到Excel 文件中:
1.将数据导出到Excel(网络下载+本地存储) http://blog.csdn.net/u010003835/article/details/50894549
2.设置单元格格式: http://blog.csdn.net/u010003835/article/details/50924454
Excel 导入, 注意 Excel 2003, Excel 2007 是不同的, 2003主要用到的类 为 HSSF 开头的类,2007 用到的类 以 XSSF 开头的类。
注意: 2007 除了基本的POI JAR包,还需要 dom4j, xmlbean 包,
这里给出这个Demo的下载地址(MyEclipse2014 下开发,喜欢的朋友在文章下面评论 或给个赞)
http://pan.baidu.com/s/1hr9qcLY
需要的Jar 包:
主要的设计思想( 程序运行的流程):
0.将 数据列(希望取得名字) 和 路径+文件名的字符串 传入方法中
1.传入文件名,根据文件名的后缀判断是Excel2003,还是Excel2007
2.读取Excel 文件,将每行的读取方式设置为abstract 抽象方法。方便对于特殊的单元格进行特殊的处理,具体的Excel特定实现
3.对于单元格的值读取 给出通用的处理方法,可以不使用这种方法,自定义处理方式
示例代码:
package util; import java.io.FileInputStream; import java.io.InputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; 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; /** * @author szh * @note 主要功能:导入Excel 文件中的数据 */ public abstract class ExcelImportUtilVerTwo { private String[] columns; protected void setColumns(String[] columns) { this.columns = columns; } public String[] getColumns() { return this.columns; } /** * @note (Excel2003)针对于xls后缀结尾的Excel。 * 读取Excel数据行,并将数据存储到Map中,具体实现的时候指定如何读取数据行 * @param tableRow * @return 返回一行Excel的数据 * @param map */ @SuppressWarnings("rawtypes") protected abstract Map readTableRowExcel2003(HSSFRow tableRow, Map map); /** * @note (Excel2007)针对于xlsx后缀结尾的Excel。 * 读取Excel数据行,并将数据存储到Map中,具体实现的时候指定如何读取数据行 * @param tableRow * @return 返回一行Excel的数据 */ @SuppressWarnings("rawtypes") protected abstract Map readTableRowExcel2007(XSSFRow tableRow, Map map); /** * @param fileName * 传入文件名 * @return 根据文件名的后缀判断传入的Excel 版本 */ protected String checkVersion(String fileName) { String version = ""; if (null == fileName || "".equals(fileName)) return version; String suffix = fileName .substring(fileName.trim().lastIndexOf(".") + 1); if ("xls".equals(suffix)) { version = "2003"; } else if ("xlsx".equals(suffix)) { version = "2007"; } return version; } /** * @note 读取excel, 将其中的数据以 List<Map> 的形式返回 * @param fileName * 读取的excel的文件名 */ @SuppressWarnings("rawtypes") public List<Map> readExcel(String fileName, String[] columns) { List<Map> list = null; this.setColumns(columns); String version = this.checkVersion(fileName); if (!"".equals(version)) { if ("2003".equals(version)) { list = readExcel2003(fileName); } else if ("2007".equals(version)) { list = readExcel2007(fileName); } } return list; } @SuppressWarnings({ "rawtypes", "unused" }) protected List<Map> readExcel2003(String fileName) { try { InputStream in = new FileInputStream(fileName); HSSFWorkbook workbook = new HSSFWorkbook(in); List<Map> list = new ArrayList<Map>(); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { HSSFSheet sheet = workbook.getSheetAt(i); if (null == sheet) continue; HSSFRow titleRow = sheet.getRow(0); // 从第一行开始读取,因为第0行是表头 for (int j = 1; j <= sheet.getLastRowNum(); j++) { HSSFRow tableRow = sheet.getRow(j); Map map = new HashMap<>(); if (null == tableRow) continue; map = this.readTableRowExcel2003(tableRow, map); list.add(map); } } in.close(); // 关闭文件 return list; // 正常返回, 返回表格的数据 } catch (Exception e) { e.printStackTrace(); return null; // 非正常返回,返回null } } @SuppressWarnings({ "rawtypes", "unused" }) protected List<Map> readExcel2007(String fileName) { try { InputStream in = new FileInputStream(fileName); XSSFWorkbook workbook = new XSSFWorkbook(in); List<Map> list = new ArrayList<Map>(); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { XSSFSheet sheet = workbook.getSheetAt(i); if (null == sheet) continue; XSSFRow tableTitle = sheet.getRow(0); for (int j = 1; j <= sheet.getLastRowNum(); j++) { XSSFRow tableRow = sheet.getRow(j); Map map = new HashMap(); if (null == tableRow) continue; map = this.readTableRowExcel2007(tableRow, map); list.add(map); } } in.close(); return list; } catch (Exception e) { e.printStackTrace(); return null; } } /** * @note 将Excel(2003)中单元格的数据 转换为String返回,可以在readTableRowExcel2003中进行自定义转换方式 * @param cell * @return 若成功则返回指定的字符串,若没有成功转换则返回null */ protected String getCellValueExcel2003(HSSFCell cell) { Boolean convertFlag = false; String cellValue = ""; if (cell == null) { convertFlag = true; } else { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); convertFlag = true; break; // 注意一个非常操蛋的事情,一般的 int 与 日期数据 都会被当成 CELL_TYPE_NUMERIC 类型 case HSSFCell.CELL_TYPE_NUMERIC: // cellValue = String.valueOf(cell.getNumericCellValue()); if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); SimpleDateFormat ymdDateConvert = new SimpleDateFormat( "yyyy-MM-dd"); cellValue = ymdDateConvert.format(date); } else { DecimalFormat comConvert = new DecimalFormat("#"); cellValue = comConvert.format(cell.getNumericCellValue()); } convertFlag = true; break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); convertFlag = true; break; case HSSFCell.CELL_TYPE_BLANK: convertFlag = true; cellValue = ""; break; } } if (convertFlag) { return cellValue; // 如果成功转换 } else { return null;// 不成功,返回null } } /** * @note 将Excel(2007)中单元格的数据 转换为String返回 ,可以在readTableRowExcel2007中进行自定义转换方式 * @param cell * @return 若成功则返回指定的字符串,若没有成功转换则返回null, */ protected String getCellValueExcel2007(XSSFCell cell) { Boolean convertFlag = false; String cellValue = ""; if (cell == null) { convertFlag = true; } else { switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_STRING: cellValue = cell.getStringCellValue(); convertFlag = true; break; // 注意一个非常操蛋的事情,一般的 int 与 日期数据 都会被当成 CELL_TYPE_NUMERIC 类型 case XSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); SimpleDateFormat ymdDateConvert = new SimpleDateFormat( "yyyy-MM-dd"); cellValue = ymdDateConvert.format(date); } else { DecimalFormat comConvert = new DecimalFormat("#"); cellValue = comConvert.format(cell.getNumericCellValue()); } convertFlag = true; break; case XSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); convertFlag = true; break; case XSSFCell.CELL_TYPE_BLANK: convertFlag = true; cellValue = ""; break; } } if (convertFlag) { return cellValue; } else { return null; } } }
测试代码:
package service; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.xssf.usermodel.XSSFRow; import util.ExcelImportUtilVerTwo; public class ExcelImportTest { public static void main(String[] args) { ExcelImportUtilVerTwo importUtilVerTwo = new ExcelImportUtilVerTwo() { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected Map readTableRowExcel2007(XSSFRow tableRow, Map map) { String[] colNames = this.getColumns(); int colNum = tableRow.getPhysicalNumberOfCells(); String cellValueString = null; for (int i = 0; i < colNum; i++) { cellValueString = this.getCellValueExcel2007(tableRow .getCell(i)); if (cellValueString != null) { map.put(colNames[i], cellValueString); } } return map; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected Map readTableRowExcel2003(HSSFRow tableRow, Map map) { String[] colNames = this.getColumns(); int colNum = tableRow.getPhysicalNumberOfCells(); String cellValueString = null; for (int i = 0; i < colNum; i++) { cellValueString = this.getCellValueExcel2003(tableRow .getCell(i)); if (cellValueString != null) { map.put(colNames[i], cellValueString); } } return map; // //自定义如何读取 // DecimalFormat df = new DecimalFormat("#"); // int colNum = tableRow.getPhysicalNumberOfCells(); // String[] colNames = this.getColumns(); // map.put(colNames[0], // df.format(tableRow.getCell(0).getNumericCellValue())); // map.put(colNames[1], tableRow.getCell(1)); // map.put(colNames[2], // df.format(tableRow.getCell(2).getNumericCellValue())); // System.out.println(HSSFDateUtil.isCellDateFormatted(tableRow // .getCell(3))); // Date date = tableRow.getCell(3).getDateCellValue(); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // String cellvalue = sdf.format(date); // map.put(colNames[3], cellvalue); // return map; } }; List<Map> list = importUtilVerTwo.readExcel( "C:\\Users\\lenovo\\Downloads\\userInfo2007.xlsx", new String[] { "iphone", "name", "password", "date" }); System.out.println(list); } }