引用依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
读取Excel文件工具类
package net.hiyana.cogniz.litecheng.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 读取Excel工具类
* @author Dhjie
*
*/
@WebServlet(name = "readExcelServlet", urlPatterns = "/readExcelServlet")
public class ReadExcelUtil extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -9037999747603051573L;
public static List<String> readExcel(File excel)
throws ServletException, IOException {
//excel文件路径
// String excelPath = "C:\\Users\\EDZ\\Desktop\\中石化源数据映射关系表(1).xlsx";
List<String> list=new ArrayList<String>();
try {
//String encoding = "GBK";
// File excel = new File(excelPath);
if (excel.isFile() && excel.exists()) { //判断文件是否存在
String[] split = excel.getName().split("\\."); //.是特殊字符,需要转义!!!!!
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(split[1])){
FileInputStream fis = new FileInputStream(excel); //文件流对象
wb = new HSSFWorkbook(fis);
}else if ("xlsx".equals(split[1])){
wb = new XSSFWorkbook(excel);
}else {
System.out.println("文件类型错误!");
return list;
}
//开始解析
Sheet sheet = wb.getSheetAt(0); //读取sheet 0
int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
HashMap<Object, Object> map = new HashMap<>();
Row row = sheet.getRow(rIndex);
Row row0 = sheet.getRow(0); //第一行
if (row != null) {
int firstCellIndex = row.getFirstCellNum(); //列
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell0=row0.getCell(cIndex);
Cell cell = row.getCell(cIndex);
if (StringUtils.isEmpty(String.valueOf(cell))) {
map.put(String.valueOf(cell0), "");
}else {
map.put(String.valueOf(cell0), String.valueOf(cell));
}
}
list.add(JSON.toJSONString(map));
}
}
return list;
} else {
System.out.println("找不到指定的文件");
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}