最近项目中有很多地方用到读取excel,记录一下!
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
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 java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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.jfinal.plugin.activerecord.Record;
import com.sdp.base.service.BsService32;
import com.sdp.plugin.db.BsDbPluginApi;
import com.sdp.plugin.db.jfinal.BsDbApi;
import com.sdp.utils.SQL;
public class ImportExcelUtil extends BsService32{
/**
* 按坐标点读取excel文件
* @param fileName
* @param sheetIndex
* @param readValues
* @return
* @throws IOException
*/
public static Map readExcel(String fileName, int sheetIndex, List readValues) throws IOException{
//按坐标点读取excel文件
Workbook wb = openWorkbook(fileName);
Sheet sheet = wb.getSheetAt(sheetIndex);// 获取文件的指定工作表m
Map map=new LinkedHashMap<>();
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();//考虑到有些表格位置值为计算的结果,这里为获取计算结果值,避免把公式读出来了
if(sheet.getLastRowNum() <= 0){
map.put("sheet", "0");
return map;
}
for (String info : readValues){//通过readValues遍历key和value
String[] zb=info.split(",");
Row row = sheet.getRow(Integer.valueOf(zb[2])-1);// 获取行
Cell cell = row.getCell(Integer.valueOf(zb[1])-1);// 获取列
CellValue cellValue = evaluator.evaluate(cell);// 获表格公式计算后的值
//DecimalFormat df = new DecimalFormat("0"); // 格式化为整数
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式化
//System.out.println(cellValue);
if(cellValue != null){
switch (cellValue.getCellType()) {// 判断值类型
case Cell.CELL_TYPE_STRING:
map.put(zb[0],cellValue.getStringValue().trim().replaceAll("%", ""));
break;
case Cell.CELL_TYPE_NUMERIC:
String dataFormat = cell.getCellStyle().getDataFormatString(); // 单元格格式
boolean isDate = DateUtil.isCellDateFormatted(cell);
if ("General".equals(dataFormat)) {
NumberFormat nf = NumberFormat.getInstance();
String s = nf.format(cellValue.getNumberValue());
if (s.indexOf(",") >= 0) {
s = s.replace(",", "").replaceAll("%", "");
}
map.put(zb[0],s);
} else if (isDate) {
map.put(zb[0],sdf.format(cellValue.getStringValue().trim().replaceAll("%", "")));
} else {
NumberFormat nf = NumberFormat.getInstance();
String s = nf.format(cellValue.getNumberValue());
if (s.indexOf(",") >= 0) {
s = s.replace(",", "").replaceAll("%", "");
}
map.put(zb[0],s);
}
break;
case Cell.CELL_TYPE_BOOLEAN:
map.put(zb[0],cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_BLANK:
map.put(zb[0],"");
break;
default:
break;
}
}else{
map.put(zb[0],null);
}
}
return map;
}
// 该方法判断excel版本
public static Workbook openWorkbook(String fileName) throws IOException,OfficeXmlFileException{
InputStream in = new FileInputStream(fileName); // 创建输入流
Workbook wb = null;
if (fileName.toLowerCase().endsWith(".xlsx")) {//toLowerCase 区分大小写
wb = new XSSFWorkbook(in);// Excel 2007
} else {
wb = new HSSFWorkbook(in);// Excel 2003
}
return wb;
}
/**搜索某一个文件中是否包含某个关键字
* @param file 待搜索的文件
* @param keyWord 要搜索的关键字
* @return
*/
public static String searchKeyWord(File file,String keyWord,int sheetIndex){
String result="0";
if (!file.exists())
System.out.println("文件不存在");
try {
Workbook wb = openWorkbook(file.getAbsolutePath());
//1.读取Excel的对象
//3.Excel工作表对象
Sheet sheet = wb.getSheetAt(sheetIndex);// 获取文件的指定工作表m
//总行数
int rowLength = sheet.getLastRowNum()+1;
//4.得到Excel工作表的行
Row hssfRow = sheet.getRow(0);
//总列数
int colLength = hssfRow.getLastCellNum();
//得到Excel指定单元格中的内容
Cell hssfCell = hssfRow.getCell(0);
//得到单元格样式
CellStyle cellStyle = hssfCell.getCellStyle();
for (int i = 0; i < rowLength; i++) {
//获取Excel工作表的行
Row hssfRow1 = sheet.getRow(i);
for (int j = 0; j < colLength; j++) {
//获取指定单元格
Cell hssfCell1 = hssfRow1.getCell(j);
if (hssfCell1 != null) {
hssfCell1.setCellType(1);
//获取每一列中的值
if(hssfCell1.getStringCellValue().toString().equals(keyWord)){
String longitude= celltype(wb,i,j+3,sheetIndex);
String laitude= celltype(wb,i,j+4,sheetIndex);
if(!longitude.equals("0") && !laitude.equals("0")){
result=longitude+"-"+laitude;
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String celltype(Workbook wb,int i,int j,int sheetIndex){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式化
String result="";
//1.读取Excel的对象
//3.Excel工作表对象
Sheet sheet = wb.getSheetAt(sheetIndex);// 获取文件的指定工作表m
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();//考虑到有些表格位置值为计算的结果,这里为获取计算结果值,避免把公式读出来了
Row row = sheet.getRow(i);// 获取行
Cell cell = row.getCell(j);// 获取列
CellValue cellValue = evaluator.evaluate(cell);
if(cellValue!=null){
switch (cellValue.getCellType()) {// 判断值类型
case Cell.CELL_TYPE_STRING:
result= cellValue.getStringValue().trim();
break;
case Cell.CELL_TYPE_NUMERIC:
String dataFormat = cell.getCellStyle().getDataFormatString(); // 单元格格式
boolean isDate = DateUtil.isCellDateFormatted(cell);
if ("General".equals(dataFormat)) {
NumberFormat nf = NumberFormat.getInstance();
String s = nf.format(cellValue.getNumberValue());
result = s;
} else if (isDate) {
result=sdf.format(cellValue.getStringValue().trim());
} else {
DecimalFormat df = new DecimalFormat("0.000");
result = df.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
result=String.valueOf(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_BLANK:
result = "";
break;
default:
break;
}
}else{
result = "0";
}
return result;
}
}