JAVA 导入excel文件
背景
–>struts2框架
–>from表单提交excel模板文件
–>java获取excel数据
步骤
1.获取excel文件
struts2 from提交会出现file地址不对情况
解决办法: 获取Filename 和contentType,保存临时文件
String target = ServletActionContext.getServletContext().getRealPath("/upload/" + fileFieldFileName);
//获取上传文件
File file = new File(target);
FileUtils.copyFile(fileField,file);
FileInputStream fis = new FileInputStream(file);
接下来就是做excel文件导入啦~(主要是获取里面的内容)
2.对Excel文件解析获取数据
代码如下:
FileInputStream fis = new FileInputStream(file);
Workbook wb;
String[] split = fileFieldFileName.split("\\.");
if ("xls".equals(split[1])){
wb = new HSSFWorkbook(fis);
}else if("xlsx".equals(split[1])){
wb=new XSSFWorkbook(fis);
}else {
return ERROR;
}
对不同版本的excel文件要用不同的poi接口
//解析workbook
Sheet sheet = wb.getSheetAt(0);//读取第一页
int firstRowNum = sheet.getFirstRowNum()+2; //获取第一行 第一和第二行为标题所以加2
int lastRowNum = sheet.getLastRowNum(); //获取最后一行
for (int i = firstRowNum; i <= lastRowNum; i++) { //遍历
Row row = sheet.getRow(i);
if (row!=null){
//获取行以后就获取每一行的cell
int firstCellNum = row.getFirstCellNum();
int lastCellNum = row.getLastCellNum();
for (int j = firstCellNum; j < lastCellNum; j++) {
Cell cell = row.getCell(j);
if (cell!=null){
System.out.println(j+":"+cell.toString());
}
}
}
cell.toString 获取的数字 原本为9 获取到为9.0
这里加了一个处理方法:
/**
* 将单元格内容转换为字符串
* @param cell
* @return
*/
private static String convertCellValueToString(Cell cell) {
if(cell==null){
return null;
}
String returnValue = null;
switch (cell.getCellType()) {
case 0: //数字
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
returnValue = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
returnValue = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
returnValue = format.format(value);
}
break;
case 1: //字符串
returnValue = cell.getStringCellValue();
break;
case 4: //布尔
Boolean booleanValue = cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
case 2: // 空值
break;
case 7: // 公式
returnValue = cell.getCellFormula();
break;
case 64: // 故障
break;
default:
break;
}
return returnValue;
}
ok,大概告成。
第一次写,下班嘻嘻
ps:迪迦!!!