一、 POI简介
Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
二、 HSSF概况
HSSF 是Horrible SpreadSheet Format的缩写,通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。
三、 POI EXCEL文档结构类
HSSFWorkbook excel文档对象 HSSFSheet excel的sheet HSSFRow excel的行 HSSFCell excel的单元格 HSSFFont excel字体 HSSFName 名称 HSSFDataFormat 日期格式 HSSFHeader sheet头 HSSFFooter sheet尾 HSSFCellStyle cell样式 HSSFDateUtil 日期 HSSFPrintSetup 打印 HSSFErrorConstants 错误信息表
四、 HSSF使用
程序清单1 ExcelMessage.java表示excel模板导入的状态信息
@MappedSuperclass
public class ExcelMessage
{
public enum Status
{
/** 成功 */
success,
/** 失败 */
fail
}
/** 返回错误消息 */
private String error;
/** 返回正确消息 */
private String ok;
/** 返回消息状态 */
private Status status;
/** 返回的url */
private String url;
/**
* 获得错误信息
*/
@JsonProperty
public String getError()
{
return error;
}
/**
* 设置错误信息
<功能详细描述>
*/
public void setError(String error)
{
this.error = error;
}
/**
* 获得正确信息
<功能详细描述>
*/
@JsonProperty
public String getOk()
{
return ok;
}
/**
* 设置正确信息
<功能详细描述>
*
* @param ok
* @see [类、类#方法、类#成员]
*/
public void setOk(String ok)
{
this.ok = ok;
}
/**
* 获得状态
<功能详细描述>
*/
public Status getStatus()
{
return status;
}
/**
* 设置状态
<功能详细描述>
*/ public void setStatus(Status status) { this.status = status; } /** * 获得返回的url
<功能详细描述>
*/ public String getUrl() { return url; } /** * 设置返回的url
<功能详细描述>
* * @param status * @see [类、类#方法、类#成员] */ public void setUrl(String url) { this.url = url; } }
程序清单2getInputStream() 获取文件字节流
public static InputStream getInputStream(MultipartFile file){
if (file == null)
return null;
logger.info(file.getOriginalFilename());
String name = file.getOriginalFilename();// 获取上传文件名,包括路径
//name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
long size = file.getSize();
if ((name == null || name.equals("")) && size == 0)
return null;
InputStream in = null;
try
{
in = file.getInputStream();
return in;
}
catch (IOException e)
{
logger.error("ExcelController importMember: 转化excel错误:"+e.getMessage());
return null;
}
}
程序清单3
validateMemberStudentTemplate()验证是否是正确的导入模板
public ExcelMessage validateMemberStudentTemplate(InputStream inputStream) throws IOException
{
ExcelMessage validateTemplateMessage = new ExcelMessage();
validateTemplateMessage.setStatus(Status.fail);
validateTemplateMessage.setError("模版不对!请下载相应模版导入且勿修改标题");
try
{
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
HSSFRow titleInfo = hssfSheet.getRow(0);
// 判断每一列标题是否正确
HSSFCell classNameCell = titleInfo.getCell(0);
if (!"班级名称(*)".equals(classNameCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell studentNoCell = titleInfo.getCell(1);
if (!"学号".equals(studentNoCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell studentNameCell = titleInfo.getCell(2);
if (!"学生姓名(*)".equals(studentNameCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell studentSexCell = titleInfo.getCell(3);
if (!"性别".equals(studentSexCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell memberNameCell = titleInfo.getCell(4);
if (!"家长1姓名(*)".equals(memberNameCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell mobileCell = titleInfo.getCell(5);
if (!"家长1手机(*)".equals(mobileCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell cardCell = titleInfo.getCell(6);
if (!"卡号1(多张用,区分)".equals(cardCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell memberTwoNameCell=titleInfo.getCell(7);
if(!"家长2姓名".equals(memberTwoNameCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell mobileTwoCell=titleInfo.getCell(8);
if(!"家长2手机".equals(mobileTwoCell.toString()))
{
return validateTemplateMessage;
}
HSSFCell cardTwoCell=titleInfo.getCell(9);
if(!"卡号2(多张用,区分)".equals(cardTwoCell.toString()))
{
return validateTemplateMessage;
}
}
catch (Exception e)
{
return validateTemplateMessage;
}
validateTemplateMessage.setStatus(Status.success);
validateTemplateMessage.setError(null);
return validateTemplateMessage;
}
程序清单4
MemberStuForms将excel文件中的数据转换为对象信息
public class MemberStuForm
{
/** 导入家长手机号 */
private String mobile;
/** 导入家长名 */
private String memberName;
/** 导入家长2手机号 */
private String mobileTwo;
/** 导入家长2名 */
private String memberNameTwo;
/** 导入学生学号 */
private String studentNo;
/** 导入学生姓名 */
private String studentName;
/** 导入班级名 */
private String className;
/** 导入卡号数组 */
private List
timeards;
/** 导入卡号2数组 */
private List
timeardsTwo;
/** 导入学生的性别 */
private Gender sex;
/** 学校 */
private DictSchool dictSchool;
/** 班级 */
private DictClass dictClass;
/** 学生ID*/
private Long stuId;
//get set略
}
public List
getMemberStuForms(InputStream inputStream, DictSchool dictSchool,
HttpServletRequest request) throws Exception
{
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(inputStream);
List
memberStuForms = new ArrayList
();
DecimalFormat df = new DecimalFormat("#");
String mobile, memberName, memberNameTwo,studentNo, mobileTwo,studentName, className, sex = null;
// start——循环工作表
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++)
{
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null)
{
continue;
}
// start—— 循环行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++)
{
HSSFRow excelInfo = hssfSheet.getRow(rowNum);
// 判空处理
if (excelInfo == null)
{
continue;
}
if (excelInfo.getCell(0) == null && excelInfo.getCell(1) == null && excelInfo.getCell(2) == null
&& excelInfo.getCell(4) == null && excelInfo.getCell(5) == null)
{
continue;
}
MemberStuForm memberStuForm = new MemberStuForm();
memberStuForm.setDictSchool(dictSchool);
// start —— 遍历列
for (int i = 0; i < excelInfo.getLastCellNum(); i++)
{
HSSFCell excelCell = excelInfo.getCell(i);
if (excelCell == null || excelCell.toString().equals(""))
{
continue;
}
/** 班级名 */
if (i == 0)
{
className = excelCell.toString();
className = className.trim();
memberStuForm.setClassName(className);
// 根据班级名设置班级
List
classes = dictClassDao.getClassByName(className, dictSchool);
if (classes != null)
{
if (classes.size() > 0)
{
memberStuForm.setDictClass(classes.get(0));
}
}
}
/** 学号 */
if (i == 1)
{
try
{
switch (excelCell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:// 数字
studentNo = df.format(excelCell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:// 字符串
studentNo = df.format(Double.parseDouble(excelCell.toString()));
break;
default:
studentNo = excelCell.toString();
break;
}
}
catch (Exception e)
{
studentNo = excelCell.toString();
}
memberStuForm.setStudentNo(studentNo);
}
/** 学生姓名 */
if (i == 2)
{
studentName = excelCell.toString();
studentName = studentName.trim();
//去掉因复制模板数据产生的空格
studentName = studentName.replaceAll((char)160+"", "");
studentName = studentName.replaceAll((char)32+"", "");
memberStuForm.setStudentName(studentName);
}
/** 学生性别 */
if (i == 3)
{
sex = excelCell.toString();
if ("男".equals(sex))
{
memberStuForm.setSex(Gender.male);
}
else if ("女".equals(sex))
{
memberStuForm.setSex(Gender.female);
}
else
{
memberStuForm.setSex(null);
}
}
/** 家长名 */
if (i == 4)
{
memberName = excelCell.toString();
memberName = memberName.trim();
//去掉因复制模板数据产生的空格
memberName = memberName.replaceAll((char)160+"", "");
memberName = memberName.replaceAll((char)32+"", "");
memberStuForm.setMemberName(memberName);
}
/** 手机 */
if (i == 5)
{
try
{
switch (excelCell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:// 数字
mobile = df.format(excelCell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:// 字符串
mobile = df.format(Double.parseDouble(excelCell.toString()));
break;
default:
mobile = excelCell.toString();
break;
}
}
catch (Exception e)
{
mobile = excelCell.toString();
}
memberStuForm.setMobile(mobile);
}
/** 卡号 */
if (i == 6)
{
String cardString = excelCell.toString();
cardString = cardString.trim();
String[] cards = cardString.replaceAll(",", ",").split(",");
if (cards != null && cards.length > 0)
{
memberStuForm.setTimeards(Arrays.asList(cards));
}
}
/** 家长2姓名*/
if (i == 7)
{
memberNameTwo = excelCell.toString();
memberNameTwo = memberNameTwo.trim();
//去掉因复制模板数据产生的空格
memberNameTwo = memberNameTwo.replaceAll((char)160+"", "");
memberNameTwo = memberNameTwo.replaceAll((char)32+"", "");
memberStuForm.setMemberNameTwo(memberNameTwo);
}
/** 家长2手机号*/
if (i == 8)
{
try
{
switch (excelCell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:// 数字
mobileTwo = df.format(excelCell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:// 字符串
mobileTwo = df.format(Double.parseDouble(excelCell.toString()));
break;
default:
mobileTwo = excelCell.toString();
break;
}
}
catch (Exception e)
{
mobileTwo = excelCell.toString();
}
memberStuForm.setMobileTwo(mobileTwo);
}
/** 卡号2 */
if (i == 9)
{
String cardString = excelCell.toString();
cardString = cardString.trim();
String[] cards = cardString.replaceAll(",", ",").split(",");
if (cards != null && cards.length > 0)
{
memberStuForm.setTimeardsTwo(Arrays.asList(cards));
}
}
}
memberStuForms.add(memberStuForm);
// end —— 遍历列
}
// end —— 循环行Row
}
// end --循环工作表
return memberStuForms;
}
@RequestMapping(value = "/batchImportExcel", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
public void batchImportExcel(FileType fileType, MultipartFile file) throws Exception
{
Map
data = new HashMap
();
if (file == null)
{
data.put("message", Message.warn("导入文件为空文件,请检查文件是否正确!"));
}
//获取1.file文件字节流
InputStream inputStream = ExcelImportUtil.getInputStream(file);
if (inputStream == null)
{
data.put("message", Message.warn("读取文件失败,请检查文件是否正确!"));
}
// 验证模版是否是正确
ExcelMessage templateMessage = excelService.validateMemberStudentTemplate(inputStream);
}