一、示例简介
本示例通过apache的poi开源包对Ms-Excel文档格式数据进行了读取解析转为Java的List序列集,该示例不但兼容了新旧(最新及97-2003的版本)版本问题,同时通过XSSF和HSSF分别解析后缀为xlsx和xls的格式文件(读写xls和xlsx格式时,HSSFWorkbook针对xls,XSSFWorkbook针对xlsx),具体代码示例如下
1. 主测试代码类ExcelReaderTest
package xwood.tools;@b@@b@import java.io.ByteArrayInputStream;@b@import java.io.ByteArrayOutputStream;@b@import java.io.DataInputStream;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.util.ArrayList;@b@import java.util.HashMap;@b@import java.util.Iterator;@b@import java.util.List;@b@import java.util.Map;@b@@b@import org.apache.poi.hssf.usermodel.HSSFRow;@b@import org.apache.poi.hssf.usermodel.HSSFSheet;@b@import org.apache.poi.hssf.usermodel.HSSFWorkbook;@b@import org.apache.poi.xssf.usermodel.XSSFRow;@b@import org.apache.poi.xssf.usermodel.XSSFSheet;@b@import org.apache.poi.xssf.usermodel.XSSFWorkbook;@b@@b@public class ExcelReaderTest {@b@ @b@ static class ExcelReader{@b@ @b@ /**excel文件位置*/@b@ private String filepath;@b@ @b@ /**读取excel为流*/@b@ private InputStream excelStream;@b@ @b@ /**将读取的excel流解析为List*/@b@ private List<Map<String, String>> list = new ArrayList<Map<String, String>>(); @b@ @b@ private Integer limit;@b@ private Integer startNum;@b@ private Integer sheetIndex;@b@ @b@ @b@ public ExcelReader(String filepath) {@b@ super();@b@ this.filepath = filepath;@b@ }@b@ @b@ @b@@b@ /**@b@ * 获取指定Excel文件的文件流@b@ * @param fileName@b@ * @throws Exception@b@ */@b@ private void readExcel2Stream(String fileName) throws Exception{@b@ InputStream fis = null;@b@ DataInputStream dis = new DataInputStream(new FileInputStream(fileName));@b@ @b@ ByteArrayOutputStream dos = new ByteArrayOutputStream();@b@ byte[] b = new byte[102];@b@ int length = 0;@b@ while ((length=dis.read(b))!=-1) {@b@ dos.write(b, 2, length-2);@b@ dos.flush();@b@ }@b@ dis.close();@b@ dos.close();@b@ fis = new ByteArrayInputStream(dos.toByteArray());@b@ excelStream = new FileInputStream(fileName);@b@ }@b@ @b@ private void parseXlsxSuffix() throws IOException{@b@ XSSFWorkbook workbook = new XSSFWorkbook(excelStream);@b@ XSSFSheet sheet = workbook.getSheetAt(sheetIndex);@b@ if (startNum == null) {@b@ startNum = sheet.getFirstRowNum();@b@ }@b@ int rows = sheet.getLastRowNum();@b@ if(rows==0)return ;@b@ XSSFRow row0 =sheet.getRow(startNum);@b@ Map<Integer, String> colsName = CellValue.getMapColNames(row0);@b@ Object[] cols = colsName.keySet().toArray();@b@ Map<String, String> line = null;@b@ for (int i = startNum + 1,num=0; i <= rows; i++) {@b@ @b@ if(sheet.getRow(i)==null)@b@ continue;//读取到那一行为空时继续向下一行@b@ line = new HashMap<String, String>();@b@ for (Object col : cols) {@b@ String data = CellValue.getStringValue(sheet.getRow(i)@b@ .getCell((Integer) col), null);@b@ String colName = colsName.get(col).trim().toLowerCase();@b@ if (data == null || data.trim().equals("")) {@b@ continue;@b@ }@b@ line.put(colName, data.trim());@b@ }@b@ if(line.size()>0){@b@ list.add(line);@b@ num++;@b@ if (num >= limit) {@b@ return ;@b@ }@b@ }@b@ }@b@ @b@ }@b@ @b@ private void parseXlsSuffix() throws IOException{@b@ HSSFWorkbook workbook =new HSSFWorkbook(excelStream);@b@ HSSFSheet sheet=workbook.getSheetAt(sheetIndex);@b@ if (startNum == null) {@b@ startNum = sheet.getFirstRowNum();@b@ }@b@ int rows = sheet.getLastRowNum();@b@ if(rows==0)return ;@b@ HSSFRow row0 =sheet.getRow(startNum);@b@ Map<Integer, String> colsName = CellValue.getMapColNames(row0);@b@ Object[] cols = colsName.keySet().toArray();@b@ Map<String, String> line = null;@b@ for (int i = startNum + 1,num=0; i <= rows; i++) {@b@ @b@ if(sheet.getRow(i)==null)@b@ continue;//读取到那一行为空时继续向下一行@b@ line = new HashMap<String, String>();@b@ for (Object col : cols) {@b@ String data = CellValue.getStringValue(sheet.getRow(i)@b@ .getCell((Integer) col), null);@b@ String colName = colsName.get(col).trim().toLowerCase();@b@ if (data == null || data.trim().equals("")) {@b@ continue;@b@ }@b@ line.put(colName, data.trim());@b@ }@b@ if(line.size()>0){@b@ list.add(line);@b@ num++;@b@ if (num >= limit) {@b@ return ;@b@ }@b@ }@b@ }@b@ @b@ @b@ }@b@ @b@ /**@b@ * 解析excel为List@b@ * @param limit 返回最大记录上限@b@ * @param startNum 开始@b@ * @param sheetIndex excel sheet号@b@ * @throws IOException@b@ */@b@ private void parseExcel() throws IOException{ @b@ String fileSiffix=filepath.substring(filepath.lastIndexOf(".")+1,filepath.length());@b@ if("xls".equalsIgnoreCase(fileSiffix))@b@ parseXlsSuffix();@b@ else if("xlsx".equalsIgnoreCase(fileSiffix))@b@ parseXlsxSuffix();@b@ }@b@ @b@ @b@ /**@b@ * 获取指定位置excel的返回数据@b@ * @param limit@b@ * @param startNum@b@ * @param sheetIndex@b@ * @return@b@ * @throws Exception@b@ */@b@ public List<Map<String, String>> getDatas(@b@ Integer limit, Integer startNum, Integer sheetIndex) throws Exception{@b@ if(filepath==null||"".equals(filepath.trim()))@b@ throw new Exception("请配置读取文件路径");@b@ this.limit=limit;@b@ this.startNum=startNum;@b@ this.sheetIndex=sheetIndex;@b@ readExcel2Stream(filepath);//存到成员变量excelStream中@b@ parseExcel();//解析存在成员变量list @b@ return list;@b@ }@b@ @b@ @b@ }@b@ @b@@b@ @SuppressWarnings("unused")@b@ public static void main(String[] args) throws Exception{@b@ ExcelReader reader=new ExcelReader("c:/NJ/bak/test123.xlsx");@b@ List<Map<String, String>> list =reader.getDatas(100,0,0);@b@ StringBuffer printMap=new StringBuffer("");@b@ for(Map<String, String> dm:list){@b@ Iterator it=dm.keySet().iterator();@b@ while(it.hasNext()){@b@ String _key=(String)it.next();@b@ printMap.append(_key+":"+dm.get(_key)+";");@b@ }@b@ @b@ }@b@ System.out.println(printMap.toString());@b@ }@b@@b@}
2. excel单元解析类CellValue
package xwood.tools;@b@@b@import java.io.BufferedReader;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.FileReader;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.InputStreamReader;@b@import java.io.PushbackInputStream;@b@import java.text.DecimalFormat;@b@import java.util.ArrayList;@b@import java.util.Date;@b@import java.util.HashMap;@b@import java.util.List;@b@import java.util.Map;@b@@b@import org.apache.poi.hssf.usermodel.HSSFCell;@b@import org.apache.poi.hssf.usermodel.HSSFDateUtil;@b@import org.apache.poi.hssf.usermodel.HSSFRow;@b@import org.apache.poi.hssf.usermodel.HSSFSheet;@b@import org.apache.poi.xssf.usermodel.XSSFCell;@b@import org.apache.poi.xssf.usermodel.XSSFRow;@b@import org.apache.poi.xssf.usermodel.XSSFSheet;@b@import org.dom4j.Document;@b@import org.dom4j.Element;@b@import org.dom4j.io.SAXReader;@b@@b@public class CellValue {@b@ public static final String TXT_SEPARATOR = "\t";@b@ public static final String XML_SEPARATOR = "root/rows/row";@b@ @b@ /**@b@ * 返回Excel2003去掉空行的记录数(xls)@b@ */@b@ public static int getRightRows(HSSFSheet sheet) {@b@ int rsRows = sheet.getPhysicalNumberOfRows(); // 行数@b@ int nullCellNum;@b@ int afterRows = rsRows;@b@ // 定义 row、cell@b@ HSSFRow row;@b@ // HSSFCell cell;@b@ String cell;@b@ // 循环输出表格中的内容@b@ for (int i = sheet.getFirstRowNum(); i < rsRows; i++) { // 统计行中为空的单元格数@b@ row = sheet.getRow(i);@b@ nullCellNum = 0;@b@ if (row == null) {@b@ afterRows--;@b@ continue;@b@ }@b@ int rsCols = row.getPhysicalNumberOfCells();// 列数@b@ try {@b@ for (int j = 0; j < rsCols; j++) {@b@ cell = row.getCell(j) == null ? "" : row.getCell(j).toString();@b@ //cell = row.getCell(j) == null ? "" : cell;@b@ if (cell==null||"".equalsIgnoreCase(cell.trim())) {@b@ nullCellNum++;@b@ }@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ if (nullCellNum >= rsCols) { // 如果nullCellNum大于或等于总的列数@b@ afterRows--; // 行数减一@b@ }@b@ }@b@ return afterRows;@b@ }@b@@b@ /**@b@ * 返回Excel2007去掉空行的记录数(xlsx)@b@ */@b@ public static int getRightRows(XSSFSheet sheet) { @b@ int rsRows = sheet.getPhysicalNumberOfRows(); // 行数@b@ int nullCellNum;@b@ int afterRows = rsRows;@b@ // 定义 row、cell@b@ XSSFRow row;@b@ // HSSFCell cell;@b@ String cell;@b@ // 循环输出表格中的内容@b@ for (int i = sheet.getFirstRowNum(); i < rsRows; i++) { // 统计行中为空的单元格数@b@ row = sheet.getRow(i);@b@ nullCellNum = 0;@b@ if (row == null) {@b@ afterRows--;@b@ continue;@b@ }@b@ int rsCols = row.getPhysicalNumberOfCells();// 列数@b@ for (int j = 0; j < rsCols; j++) {@b@ cell = row.getCell(j) == null ? "" : row.getCell(j).toString();@b@ if ("".equals(cell.trim())) {@b@ nullCellNum++;@b@ }@b@ }@b@ if (nullCellNum >= rsCols) { // 如果nullCellNum大于或等于总的列数@b@ afterRows--; // 行数减一@b@ }@b@ }@b@ return afterRows;@b@ }@b@@b@ /**@b@ * excel2003单元格内容读取@b@ * @b@ * @param cell@b@ * @param defaultValue@b@ * @return@b@ */@b@ @SuppressWarnings("deprecation")@b@ public static String getStringValue(HSSFCell cell, String defaultValue) {@b@ String strReturn = defaultValue;@b@ try {@b@ @b@ if (cell == null)@b@ return defaultValue;@b@ @b@ int type = cell.getCellType();@b@ @b@ @b@ switch (type) {@b@ case HSSFCell.CELL_TYPE_STRING:@b@ strReturn = cell.getStringCellValue();@b@ break;@b@ case HSSFCell.CELL_TYPE_NUMERIC:@b@ try {@b@ boolean isDate = HSSFDateUtil.isCellDateFormatted(cell);@b@ @b@ if (isDate) {@b@ double d = cell.getNumericCellValue();@b@ Date date = HSSFDateUtil.getJavaDate(d);@b@ @b@ if (strReturn == null) {@b@ strReturn = cell.getDateCellValue().toLocaleString();@b@ }@b@ } else {@b@ double d = cell.getNumericCellValue();@b@ strReturn = keepScore(d);@b@ }@b@ } catch (Exception e) {@b@ double d = cell.getNumericCellValue();@b@ strReturn = keepScore(d);@b@ }@b@ break;@b@ case HSSFCell.CELL_TYPE_BOOLEAN:@b@ strReturn = String.valueOf(cell.getBooleanCellValue());@b@ break;@b@ case HSSFCell.CELL_TYPE_ERROR:@b@ strReturn = defaultValue;@b@ break;@b@ default:@b@ strReturn = defaultValue;@b@@b@ }@b@ @b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ strReturn = defaultValue;@b@ }@b@@b@ return strReturn;@b@ }@b@@b@ /**@b@ * excel2007单元格内容读取@b@ * @b@ * @param cell@b@ * @param defaultValue@b@ * @return@b@ */@b@ @SuppressWarnings("deprecation")@b@ public static String getStringValue(XSSFCell cell, String defaultValue) {@b@ String strReturn = defaultValue;@b@@b@ try {@b@ if (cell == null)@b@ return defaultValue;@b@@b@ int type = cell.getCellType();@b@@b@ switch (type) {@b@ case XSSFCell.CELL_TYPE_STRING:@b@ strReturn = cell.getStringCellValue();@b@ break;@b@ case XSSFCell.CELL_TYPE_NUMERIC:@b@ boolean isDate = HSSFDateUtil.isCellDateFormatted(cell);@b@ if (isDate) {@b@ double d = cell.getNumericCellValue();@b@ Date date = HSSFDateUtil.getJavaDate(d);@b@@b@ if (strReturn == null) {@b@ strReturn = cell.getDateCellValue().toLocaleString();@b@ }@b@ } else {@b@ double d = cell.getNumericCellValue();@b@ strReturn = keepScore(d);@b@ }@b@ break;@b@ case XSSFCell.CELL_TYPE_BOOLEAN:@b@ strReturn = String.valueOf(cell.getBooleanCellValue());@b@ break;@b@ case XSSFCell.CELL_TYPE_ERROR:@b@ strReturn = defaultValue;@b@ break;@b@ default:@b@ strReturn = defaultValue;@b@@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ strReturn = defaultValue;@b@ }@b@@b@ return strReturn;@b@ }@b@@b@@b@ /**@b@ * 获取excel2003标题行列名组成的list@b@ * @b@ * @param row 标题行@b@ * @return list@b@ */@b@ public static List<String> getColNames(HSSFRow row) {@b@ int cols = row.getPhysicalNumberOfCells();@b@ List<String> colNames = new ArrayList<String>();@b@@b@ for (int i = 0; i < cols; i++) {@b@ String colName = getStringValue(row.getCell(i), "");@b@ if (colName != null && !colName.equals(""))@b@ colNames.add(colName.trim().toLowerCase());@b@ }@b@@b@ return colNames;@b@ }@b@@b@ /**@b@ * 获取excel2003标题行列名组成的list@b@ * @b@ * @param row 标题行@b@ * @return list@b@ */@b@ public static Map<Integer, String> getMapColNames(HSSFRow row) {// HSSFRow row@b@ int cols = row.getPhysicalNumberOfCells();//获得总列数@b@ @b@ @b@ Map<Integer, String> colNames = new HashMap<Integer, String>();@b@ @b@ for (int i = 0; i <cols; i++) {@b@ @b@ String colName = getStringValue(row.getCell(i), "");//读取Excel中的数据@b@ @b@ if(colName.equals("")){@b@ cols++;@b@ }@b@ if (colName != null && !colName.equals("")){@b@ colNames.put(i, colName.trim());@b@ }@b@ }@b@@b@ return colNames;@b@ }@b@@b@ /**@b@ * 获取excel2007标题行列名组成的list@b@ * @b@ * @param row 标题行@b@ * @return list@b@ */@b@ public static List<String> getColNames(XSSFRow row) {@b@ int cols = row.getPhysicalNumberOfCells();@b@@b@ List<String> colNames = new ArrayList<String>();@b@@b@ for (int i = 0; i < cols; i++) {@b@ String colName = getStringValue(row.getCell(i), "");@b@ if (colName != null && !colName.equals(""))@b@ colNames.add(colName.trim().toLowerCase());@b@ }@b@@b@ return colNames;@b@ }@b@@b@ /**@b@ * 获取excel2007标题行列名组成的list@b@ * @b@ * @param row 标题行@b@ * @return list@b@ */@b@ public static Map<Integer, String> getMapColNames(XSSFRow row) {@b@ int cols = row.getPhysicalNumberOfCells();@b@@b@ Map<Integer, String> colNames = new HashMap<Integer, String>();@b@@b@ for (int i = 0; i < cols; i++) {@b@ String colName = getStringValue(row.getCell(i), "");@b@ @b@ if(colName.equals("")){//如果colName为空时 cols就加1@b@ cols++;@b@ }@b@ if (colName != null && !colName.equals(""))@b@ colNames.put(i, colName.trim());@b@ }@b@@b@ return colNames;@b@ }@b@@b@ /**@b@ * 获取txt标题行列名组成的list(默认第一个非空行为标题行)@b@ * @b@ * @param fieName 文件名@b@ * @return list@b@ */@b@ public static List<String> getColNames(String fileName, String separator) {@b@ BufferedReader in = null;@b@ try {@b@ List<String> colNames = new ArrayList<String>();@b@ in = new BufferedReader(new FileReader(fileName));@b@ String line;@b@ while ((line = in.readLine()) != null) {@b@ if (!"".equals(line.trim())) {@b@ for (String str : line.split(separator)) {@b@ colNames.add(str.trim());@b@ }@b@ return colNames;@b@ }@b@ }@b@ @b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ } finally {@b@ try {@b@ if (in != null){@b@ in.close();@b@ }@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return null;@b@ }@b@@b@ /**@b@ * 获取txt标题行列名组成的list(默认第一个非空行为标题行)@b@ * @b@ * @param fieName 文件名@b@ * @return list@b@ */@b@ public static Map<Integer, String> getMapColNames(String fileName,@b@ String separator) {@b@ BufferedReader in = null;@b@ try {@b@ Map<Integer, String> colNames = new HashMap<Integer, String>();@b@ in = new BufferedReader(new FileReader(fileName));@b@ String line;@b@ while ((line = in.readLine()) != null) {@b@ if (!"".equals(line.trim())) {@b@ for (int i = 0; i < line.split(separator).length; i++) {@b@ String str = line.split(separator)[i];@b@ colNames.put(i, str.trim());@b@ }@b@ return colNames;@b@ }@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }finally{@b@ try {@b@ if (in != null){@b@ in.close();@b@ }@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return null;@b@ }@b@ public static Map<Integer, String> getMapColNames(InputStream fis,@b@ String separator) {@b@ BufferedReader in = null;@b@ try {@b@ Map<Integer, String> colNames = new HashMap<Integer, String>();@b@ in = new BufferedReader(new InputStreamReader(fis));@b@ String line;@b@ while ((line = in.readLine()) != null) {@b@ if (!"".equals(line.trim())) {@b@ for (int i = 0; i < line.split(separator).length; i++) {@b@ String str = line.split(separator)[i];@b@ colNames.put(i, str.trim());@b@ }@b@ return colNames;@b@ }@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }finally{@b@ try {@b@ if (in != null){@b@ in.close();@b@ }@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return null;@b@ }@b@ /**@b@ * 获取txt标题行列名组成的list(默认第一个非空行为标题行)@b@ * @b@ * @param fieName 文件名@b@ * @return list@b@ */@b@ public static List<String> getColNames(InputStream is, boolean firstHeader,@b@ String separator) {@b@ BufferedReader in = null;@b@ try {@b@ List<String> colNames = new ArrayList<String>();@b@ in = new BufferedReader(new InputStreamReader(is));@b@ String line = null;@b@ boolean isRun = true;@b@ while (isRun) {@b@ line = in.readLine();@b@ if (line == null) {@b@ continue;@b@ }@b@ isRun = false;@b@ if (!firstHeader) {@b@ line = in.readLine();@b@ }@b@ }@b@ if (!"".equals(line.trim())) {@b@ for (int i = 0; i < line.split(separator).length; i++) {@b@ String str = line.split(separator)[i];@b@ colNames.add(str.trim());@b@ }@b@ return colNames;@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ finally{@b@ try {@b@ if (in != null){@b@ in.close();@b@ }@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return null;@b@ }@b@@b@ /**@b@ * 获取txt标题行列名组成的list(默认第一个非空行为标题行)@b@ * @b@ * @param fieName 文件名@b@ * @return list@b@ */@b@ public static Map<Integer, String> getMapColNames(InputStream is,@b@ boolean firstHeader, String separator) {@b@ BufferedReader in = null;@b@ try {@b@ Map<Integer, String> colNames = new HashMap<Integer, String>();@b@ in = new BufferedReader(new InputStreamReader(is));@b@ String line = null;@b@ boolean isRun = true;@b@ while (isRun) {@b@ line = in.readLine();@b@ if (line == null) {@b@ continue;@b@ }@b@ isRun = false;@b@ if (!firstHeader) {@b@ line = in.readLine();@b@ }@b@ }@b@ if (!"".equals(line.trim())) {@b@ for (int i = 0; i < line.split(separator).length; i++) {@b@ String str = line.split(separator)[i];@b@ colNames.put(i, str.trim());@b@ }@b@ return colNames;@b@ }@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ finally{@b@ try {@b@ if (in != null){@b@ in.close();@b@ }@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return null;@b@ }@b@@b@ /**@b@ * 获取txt内容组成的list(默认第一个非空行为标题行)@b@ * @b@ * @param fieName 文件名@b@ * @return list@b@ */@b@ public static List<String[]> getTxtContents(String fileName,@b@ String separator) {@b@ BufferedReader in = null;@b@ try {@b@ List<String[]> colNames = new ArrayList<String[]>();@b@ in = new BufferedReader(new FileReader(fileName));@b@ String line;@b@ while ((line = in.readLine()) != null) {@b@ if (!"".equals(line.trim())) {@b@ colNames.add(line.split(separator));@b@ }@b@ }@b@ colNames.remove(0);@b@ return colNames;@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ } finally{@b@ try {@b@ if (in != null){@b@ in.close();@b@ }@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return null;@b@ }@b@ public static List<String[]> getTxtContents(InputStream fis,@b@ String separator) {@b@ @b@ BufferedReader in = null;@b@ try {@b@ List<String[]> colNames = new ArrayList<String[]>();@b@ in = new BufferedReader(new InputStreamReader(fis));@b@ String line;@b@ while ((line = in.readLine()) != null) {@b@ if (!"".equals(line.trim())) {@b@ colNames.add(line.split(separator));@b@ }@b@ }@b@ colNames.remove(0);@b@ return colNames;@b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ } finally{@b@ try {@b@ if (in != null){@b@ in.close();@b@ }@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return null;@b@ }@b@ /**@b@ * 返回xml文件对应的内容@b@ */@b@ public static Document getXmlDoc(File file) {@b@ SAXReader reader = new SAXReader();@b@ Document document = null;@b@ try {@b@ document = reader.read(file);@b@ } catch (Exception e) {@b@ InputStream in = null;@b@ InputStreamReader strInStream = null;@b@ try {@b@ in = new FileInputStream(file);@b@ strInStream = new InputStreamReader(in, "GBK");@b@ document = reader.read(strInStream);@b@ } catch (Exception ex) {@b@ ex.printStackTrace();@b@ } finally{@b@ try {@b@ if (strInStream!=null) strInStream.close();@b@ } catch (IOException e1) {@b@ e1.printStackTrace();@b@ }@b@ try {@b@ if (in!=null) in.close();@b@ } catch (IOException e1) {@b@ e1.printStackTrace();@b@ }@b@ }@b@@b@ }@b@ return document;@b@ }@b@@b@ /**@b@ * 返回xml文件对应的内容@b@ */@b@ public static Document getXmlDoc(InputStream fis) {@b@ Document document = null;@b@ SAXReader reader = new SAXReader();@b@ try {@b@ BufferedReader input = null;@b@ PushbackInputStream pis = new PushbackInputStream(fis, 1024);@b@ String bomEncoding = getBOMEncoding(pis);@b@ if (bomEncoding == null) {@b@ input = new BufferedReader(new InputStreamReader(pis, "UTF-8"));@b@ } else {@b@ input = new BufferedReader(new InputStreamReader(pis,@b@ bomEncoding));@b@ }@b@ document = reader.read(input);@b@ } catch (Exception e) {@b@ try {@b@ InputStreamReader strInStream = new InputStreamReader(fis, "GBK");@b@ document = reader.read(strInStream);@b@ } catch (Exception ex) {@b@ ex.printStackTrace();@b@ }@b@ }@b@ return document;@b@ }@b@@b@ /**@b@ * 获取xml最后一级节点名组成的list@b@ * @b@ * @param element0 节点@b@ * @return list@b@ */@b@ public static List<String> getLastLevelNodeNames(Element element0) {@b@ List<String> nodeNames = new ArrayList<String>();@b@ @SuppressWarnings("unchecked")@b@ List<Element> elements = element0.elements();@b@ for (Element ele : elements) {@b@ nodeNames.add(ele.getName());@b@ }@b@ return nodeNames;@b@ }@b@@b@ protected static String getBOMEncoding(PushbackInputStream is)@b@ throws IOException {@b@ String encoding = null;@b@ int[] bytes = new int[3];@b@ bytes[0] = is.read();@b@ bytes[1] = is.read();@b@ bytes[2] = is.read();@b@ if (bytes[0] == 0xFE && bytes[1] == 0xFF) {@b@ encoding = "UTF-16BE";@b@ is.unread(bytes[2]);@b@ } else if (bytes[0] == 0xFF && bytes[1] == 0xFE) {@b@ encoding = "UTF-16LE";@b@ is.unread(bytes[2]);@b@ } else if (bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) {@b@ encoding = "UTF-8";@b@ } else {@b@ for (int i = bytes.length - 1; i >= 0; i--) {@b@ is.unread(bytes[i]);@b@ }@b@ }@b@ return encoding;@b@ }@b@@b@ private static String keepScore(double d) {@b@ String result = "";@b@ if (d > 0) {@b@ if (d - (int) d < Double.MIN_VALUE) { // 是否为int型@b@ result = Integer.toString((int) d);@b@ } else { // 是否为double型@b@ DecimalFormat df = new DecimalFormat("#.###########");@b@ result = df.format(d);@b@ // strReturn = Double.toString(cell.getNumericCellValue());@b@ }@b@ } else {@b@ if ((int) d - d < Double.MIN_VALUE) { // 是否为int型@b@ result = Integer.toString((int) d);@b@ } else { // 是否为double型@b@ DecimalFormat df = new DecimalFormat("#.###########");@b@ result = df.format(d);@b@ }@b@ }@b@ return result;@b@ }@b@}
二、控制台结果
id:12;title:xwood;date:8.9;
三、依赖jar包
commons-codec-1.6.jar,点击下载
commons-logging-1.1.1.jar,点击下载
dom4j-1.6.1.jar,点击下载
log4j-1.2.17.jar,点击下载
poi-3.9.jar,点击下载
poi-ooxml-3.9.jar,点击下载
poi-ooxml-schemas-3.9.jar,点击下载
xmlbeans-2.3.0.jar,点击下载