Java--POI读取excel文件

来源:互联网 发布:法式文胸 知乎 编辑:程序博客网 时间:2024/04/30 13:18


package test;import java.util.List;import example.ExcelReaderExample;public class Test {public static void main(String[] args) {ExcelReaderExample example = new ExcelReaderExample();List<String> list = example.readerExcel("file//example.xlsx");for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}}}


package example;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.DateUtil;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;public class ExcelReaderExample {private XSSFWorkbook xssfWorkbook;/** *  * @param excel文件路径 * @return */public List<String> readerExcel(String path) {List<String> list = new ArrayList<String>();try {if (path != null) {xssfWorkbook = new XSSFWorkbook(path);// 2.获取sheet的数量int sheetCount = xssfWorkbook.getNumberOfSheets();// 3.遍历每一个sheetfor (int i = 0; i < sheetCount; i++) {// 3.1.获取excel工作表对象XSSFSheet sheet = xssfWorkbook.getSheetAt(i);// 3.2获取总行数int totalRows = sheet.getPhysicalNumberOfRows();// 3.3遍历每一行for (int j = 0; j < totalRows; j++) {String rowValue = null;XSSFRow row = sheet.getRow(j);// 3.4获取每行总列数int totalCells = row.getPhysicalNumberOfCells();// 3.5循环每一列for (int k = 0; k < totalCells; k++) {String cellValue = null;// 3.5 获取单元格XSSFCell cell = row.getCell(k);int cellType = cell.getCellType();// 3.6 判断单元格类型switch (cellType) {case Cell.CELL_TYPE_NUMERIC: // 数字、日期if (DateUtil.isInternalDateFormat(cellType)) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");cellValue = simpleDateFormat.format(cell.getDateCellValue());} else {cellValue = String.valueOf(cell.getNumericCellValue());}break;case Cell.CELL_TYPE_STRING: // 文本cellValue = cell.getStringCellValue();break;case Cell.CELL_TYPE_FORMULA: // 公式break;case Cell.CELL_TYPE_BLANK: // 空白continue;case Cell.CELL_TYPE_BOOLEAN: // 布尔cellValue = String.valueOf(cell.getBooleanCellValue());break;case Cell.CELL_TYPE_ERROR: // 错误break;default:break;}rowValue += "," + cellValue;}if (rowValue == null) {continue;}String[] tempStr = rowValue.split(",");// 除去为null的字符串rowValue = tempStr[1];for (int k = 2; k < tempStr.length; k++) {rowValue += "," + tempStr[k];}list.add(rowValue);}}}} catch (IOException e) {e.printStackTrace();}return list;}}




0 0
原创粉丝点击