excel读取 工具类

JAVA源码如下:

  1 package cn.yongche.utils;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 import org.apache.poi.hssf.usermodel.HSSFCell;
 10 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 11 import org.apache.poi.ss.usermodel.Cell;
 12 import org.apache.poi.ss.usermodel.Row;
 13 import org.apache.poi.ss.usermodel.Sheet;
 14 import org.apache.poi.ss.usermodel.Workbook;
 15 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 16 
 17 /**
 18  * excel读取 工具类
 19  * 
 20  * @jar包
 21  *      该类使用到了以下jar:
 22  *      1、poi-ooxml-3.9.jar
 23  *      2、poi-3.9.jar
 24  */
 25 public class ImportExecl {
 26 
 27     /**
 28      * main测试
 29      */
 30     public static void main(String[] args) throws Exception {
 31         ImportExecl poi = new ImportExecl();
 32         List<List<String>> list = poi.read("E:/批量导入客户模板.xlsx");
 33         if (list != null) {
 34             for (int i = 0; i < list.size(); i++) {
 35                 List<String> cellList = list.get(i);
 36                 for (int j = 0; j < cellList.size(); j++) {
 37                     System.out.print("    " + cellList.get(j));
 38                 }
 39                 System.out.println();
 40             }
 41         }
 42     }
 43 
 44     //总行数
 45     private int totalRows = 0;
 46 
 47     //总列数
 48     private int totalCells = 0;
 49 
 50     //错误信息
 51     private String errorInfo;
 52 
 53     //构造方法
 54     public ImportExecl() {
 55     }
 56 
 57     /**
 58      * 得到总行数
 59      */
 60     public int getTotalRows() {
 61         return totalRows;
 62     }
 63 
 64     /**
 65      * 得到总列数
 66      */
 67     public int getTotalCells() {
 68         return totalCells;
 69     }
 70 
 71     /**
 72      * 得到错误信息
 73      */
 74     public String getErrorInfo() {
 75         return errorInfo;
 76     }
 77 
 78     /**
 79      * 验证excel文件
 80      */
 81     public boolean validateExcel(String filePath) {
 82         /** 检查文件名是否为空或者是否是Excel格式的文件 */
 83         if (filePath == null || !(CheckExcelUtil.isExcel2003(filePath) || CheckExcelUtil.isExcel2007(filePath))) {
 84             errorInfo = "文件名不是excel格式";
 85             return false;
 86         }
 87 
 88         /** 检查文件是否存在 */
 89         File file = new File(filePath);
 90         if (file == null || !file.exists()) {
 91             errorInfo = "文件不存在";
 92             return false;
 93         }
 94         return true;
 95     }
 96 
 97     /**
 98      * 根据文件路径读取excel文件
 99      */
100     public List<List<String>> read(String filePath) throws IOException {
101         List<List<String>> dataLst = new ArrayList<List<String>>();
102         InputStream is = null;
103         try {
104             /** 验证文件是否合法 */
105             if (!validateExcel(filePath)) {
106                 System.out.println(errorInfo);
107                 return null;
108             }
109 
110             /** 判断文件的类型,是2003还是2007 */
111             boolean isExcel2003 = true;
112             if (CheckExcelUtil.isExcel2007(filePath)) {
113                 isExcel2003 = false;
114             }
115 
116             /** 调用本类提供的根据流读取的方法 */
117             File file = new File(filePath);
118             is = new FileInputStream(file);
119             dataLst = read(is, isExcel2003);
120             is.close();
121             is = null;
122         } catch (Exception ex) {
123             ex.printStackTrace();
124         } finally {
125             if (is != null) {
126                 try {
127                     is.close();
128                 } catch (IOException e) {
129                     is = null;
130                     e.printStackTrace();
131                 }
132             }
133         }
134         return dataLst;
135     }
136 
137     /**
138      * 根据流读取Excel文件
139      * 
140      * @param inputStream 文件输入流
141      * @param isExcel2003 标识是否2003的excel。
142  *                        true:是2003的excel,false:是2007的excel
143      * @return
144      * 
145      * @扩展说明 
146      *          如果使用springmvc的MultipartFile接收前端上传的excel文件的话,可以使用MultipartFile的对象,获取上传的文件名称,
147      *          然后,可以通过 CheckExcelUtil 类的方法,接收文件名称参数,来判断excel所属的版本。最后再调用此方法来读取excel数据。
148      * 
149      */
150     public List<List<String>> read(InputStream inputStream, boolean isExcel2003) {
151         List<List<String>> dataLst = null;
152         try {
153             /** 根据版本选择创建Workbook的方式 */
154             Workbook wb = null;
155             if (isExcel2003) {
156                 wb = new HSSFWorkbook(inputStream);
157             } else {
158                 wb = new XSSFWorkbook(inputStream);
159             }
160             dataLst = read(wb);
161         } catch (IOException e) {
162             e.printStackTrace();
163         }
164         return dataLst;
165     }
166 
167     /**
168      * 读取数据
169      */
170     private List<List<String>> read(Workbook wb) {
171         List<List<String>> dataLst = new ArrayList<List<String>>();
172         //得到第一个shell
173         Sheet sheet = wb.getSheetAt(0);
174         //得到Excel的行数
175         this.totalRows = sheet.getPhysicalNumberOfRows();
176         //得到Excel的列数
177         if (this.totalRows >= 1 && sheet.getRow(0) != null) {
178             this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
179         }
180 
181         //循环Excel的行
182         for (int r = 0; r < this.totalRows; r++) {
183             Row row = sheet.getRow(r);
184             if (row == null) {
185                 continue;
186             }
187             List<String> rowLst = new ArrayList<String>();
188             //循环Excel的列
189             for (int c = 0; c < this.getTotalCells(); c++) {
190                 Cell cell = row.getCell(c);
191                 String cellValue = "";
192                 if (null != cell) {
193                     // 以下是判断数据的类型
194                     switch (cell.getCellType()) {
195                     case HSSFCell.CELL_TYPE_NUMERIC: // 数字
196                         cellValue = cell.getNumericCellValue() + "";
197                         break;
198 
199                     case HSSFCell.CELL_TYPE_STRING: // 字符串
200                         cellValue = cell.getStringCellValue();
201                         break;
202 
203                     case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
204                         cellValue = cell.getBooleanCellValue() + "";
205                         break;
206 
207                     case HSSFCell.CELL_TYPE_FORMULA: // 公式
208                         cellValue = cell.getCellFormula() + "";
209                         break;
210 
211                     case HSSFCell.CELL_TYPE_BLANK: // 空值
212                         cellValue = "";
213                         break;
214 
215                     case HSSFCell.CELL_TYPE_ERROR: // 故障
216                         cellValue = "非法字符";
217                         break;
218 
219                     default:
220                         cellValue = "未知类型";
221                         break;
222                     }
223                 }
224                 rowLst.add(cellValue);
225             }
226 
227             //保存第r行的第c列
228             dataLst.add(rowLst);
229         }
230         return dataLst;
231     }
232 
233 }
234 
235 class CheckExcelUtil {
236     /**
237      * 检查是否是2003的excel,若是,则返回true
238      */
239     public static boolean isExcel2003(String filePath) {
240         return filePath.matches("^.+\.(?i)(xls)$");
241     }
242 
243     /**
244      * 检查是否是2007的excel,若是,则返回true
245      */
246     public static boolean isExcel2007(String filePath) {
247         return filePath.matches("^.+\.(?i)(xlsx)$");
248     }
249 }
原文地址:https://www.cnblogs.com/zhoubang521/p/5200161.html