excelUtil
温嘉赐
2023-12-01
package cn.net.zzfz.center.common.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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 com.alibaba.fastjson.JSON;
public class ExcelUtil {
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 读取excel
* @param fileName
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static List<Map<String, Object>> uploadFile(String fileName) throws FileNotFoundException, IOException {
return uploadFile(fileName,0 , 0);
}
/***
*
* @param fileName
* @param top 第几行为开始标题行,从0开始算
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static List<Map<String, Object>> uploadFile(String fileName,int sheetat, int top) throws FileNotFoundException, IOException {
boolean isE2007 = false; // 判断是否是excel2007格式
if (fileName.endsWith("xlsx"))
isE2007 = true;
InputStream input = new FileInputStream(fileName); // 建立输入流
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Workbook workbook = null;
if (isE2007)
workbook = new XSSFWorkbook(input);
else
workbook = new HSSFWorkbook(input);
Sheet sheet = workbook.getSheetAt(sheetat);
Row topRow = sheet.getRow(top);
int count = sheet.getLastRowNum();
for (int i = top+1; i <= count; i++) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
Row row = sheet.getRow(i);
for (Iterator<Cell> it = row.cellIterator(); it.hasNext();) {
Cell cell = it.next();
String cellValue = StringUtils.trimToEmpty(topRow.getCell(cell.getColumnIndex()).getStringCellValue());
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if(HSSFDateUtil.isCellDateFormatted(cell)){
if(HSSFDateUtil.isCellDateFormatted(cell)){
map.put(cellValue, sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString());
}else{
map.put(cellValue, cell.getNumericCellValue());
}
}else{
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);//true时的格式:1,234,567,890
String cv = nf.format(cell.getNumericCellValue());
map.put(cellValue, cv);
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
map.put(cellValue, cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
String cvalue = StringUtils.isBlank(cell.getStringCellValue()) ? " " : cell.getStringCellValue();
map.put(cellValue, cvalue);
}
}
if(map.isEmpty()){
continue;
}
list.add(map);
}
return list;
}
}