Java SpringMVC POI上传excel并读取文件内容
用的SSM框架,所需要的jar包如图所示:,链接地址:jar包下载 ,下面直接上代码。
1、ExcelUtil工具类
[java] view plain copy
- <span style="color:#993399;"><span style="font-size:18px;color:#993399;">import java.text.DecimalFormat;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFDateUtil;
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.DateUtil;
- import org.apache.poi.xssf.usermodel.XSSFCell;
- /**
- * Excel工具类
- * @author lp
- *
- */
- public class ExcelUtil {
- public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
- public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
- public static final String EMPTY = "";
- public static final String POINT = ".";
- public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
- /**
- * 获得path的后缀名
- * @param path
- * @return
- */
- public static String getPostfix(String path){
- if(path==null || EMPTY.equals(path.trim())){
- return EMPTY;
- }
- if(path.contains(POINT)){
- return path.substring(path.lastIndexOf(POINT)+1,path.length());
- }
- return EMPTY;
- }
- /**
- * 单元格格式
- * @param hssfCell
- * @return
- */
- @SuppressWarnings({ "static-access", "deprecation" })
- public static String getHValue(HSSFCell hssfCell){
- if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
- return String.valueOf(hssfCell.getBooleanCellValue());
- } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
- String cellValue = "";
- if(HSSFDateUtil.isCellDateFormatted(hssfCell)){
- Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());
- cellValue = sdf.format(date);
- }else{
- DecimalFormat df = new DecimalFormat("#.##");
- cellValue = df.format(hssfCell.getNumericCellValue());
- String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
- if(strArr.equals("00")){
- cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
- }
- }
- return cellValue;
- } else {
- return String.valueOf(hssfCell.getStringCellValue());
- }
- }
- /**
- * 单元格格式
- * @param xssfCell
- * @return
- */
- public static String getXValue(XSSFCell xssfCell){
- if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
- return String.valueOf(xssfCell.getBooleanCellValue());
- } else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
- String cellValue = "";
- if(XSSFDateUtil.isCellDateFormatted(xssfCell)){
- Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());
- cellValue = sdf.format(date);
- }else{
- DecimalFormat df = new DecimalFormat("#.##");
- cellValue = df.format(xssfCell.getNumericCellValue());
- String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
- if(strArr.equals("00")){
- cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
- }
- }
- return cellValue;
- } else {
- return String.valueOf(xssfCell.getStringCellValue());
- }
- }
- /**
- * 自定义xssf日期工具类
- * @author lp
- *
- */
- class XSSFDateUtil extends DateUtil{
- protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
- return DateUtil.absoluteDay(cal, use1904windowing);
- }
- }</span></span>
2、ExcelRead:读取Excel类
[java] view plain copy
- package com.ssm.util;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFRow;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.xssf.usermodel.XSSFCell;
- import org.apache.poi.xssf.usermodel.XSSFRow;
- import org.apache.poi.xssf.usermodel.XSSFSheet;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- import org.springframework.web.multipart.MultipartFile;
- /**
- * 读取Excel
- * @author lp
- *
- */
- public class ExcelRead {
- public int totalRows; //sheet中总行数
- public static int totalCells; //每一行总单元格数
- /**
- * read the Excel .xlsx,.xls
- * @param file jsp中的上传文件
- * @return
- * @throws IOException
- */
- public List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {
- if(file==null||ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())){
- return null;
- }else{
- String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());
- if(!ExcelUtil.EMPTY.equals(postfix)){
- if(ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
- return readXls(file);
- }else if(ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
- return readXlsx(file);
- }else{
- return null;
- }
- }
- }
- return null;
- }
- /**
- * read the Excel 2010 .xlsx
- * @param file
- * @param beanclazz
- * @param titleExist
- * @return
- * @throws IOException
- */
- @SuppressWarnings("deprecation")
- public List<ArrayList<String>> readXlsx(MultipartFile file){
- List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
- // IO流读取文件
- InputStream input = null;
- XSSFWorkbook wb = null;
- ArrayList<String> rowList = null;
- try {
- input = file.getInputStream();
- // 创建文档
- wb = new XSSFWorkbook(input);
- //读取sheet(页)
- for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
- XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
- if(xssfSheet == null){
- continue;
- }
- totalRows = xssfSheet.getLastRowNum();
- //读取Row,从第二行开始
- for(int rowNum = 1;rowNum <= totalRows;rowNum++){
- XSSFRow xssfRow = xssfSheet.getRow(rowNum);
- if(xssfRow!=null){
- rowList = new ArrayList<String>();
- totalCells = xssfRow.getLastCellNum();
- //读取列,从第一列开始
- for(int c=0;c<=totalCells+1;c++){
- XSSFCell cell = xssfRow.getCell(c);
- if(cell==null){
- rowList.add(ExcelUtil.EMPTY);
- continue;
- }
- rowList.add(ExcelUtil.getXValue(cell).trim());
- }
- list.add(rowList);
- }
- }
- }
- return list;
- } catch (IOException e) {
- e.printStackTrace();
- } finally{
- try {
- input.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- /**
- * read the Excel 2003-2007 .xls
- * @param file
- * @param beanclazz
- * @param titleExist
- * @return
- * @throws IOException
- */
- public List<ArrayList<String>> readXls(MultipartFile file){
- List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
- // IO流读取文件
- InputStream input = null;
- HSSFWorkbook wb = null;
- ArrayList<String> rowList = null;
- try {
- input = file.getInputStream();
- // 创建文档
- wb = new HSSFWorkbook(input);
- //读取sheet(页)
- for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
- HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
- if(hssfSheet == null){
- continue;
- }
- totalRows = hssfSheet.getLastRowNum();
- //读取Row,从第二行开始
- for(int rowNum = 1;rowNum <= totalRows;rowNum++){
- HSSFRow hssfRow = hssfSheet.getRow(rowNum);
- if(hssfRow!=null){
- rowList = new ArrayList<String>();
- totalCells = hssfRow.getLastCellNum();
- //读取列,从第一列开始
- for(short c=0;c<=totalCells+1;c++){
- HSSFCell cell = hssfRow.getCell(c);
- if(cell==null){
- rowList.add(ExcelUtil.EMPTY);
- continue;
- }
- rowList.add(ExcelUtil.getHValue(cell).trim());
- }
- list.add(rowList);
- }
- }
- }
- return list;
- } catch (IOException e) {
- e.printStackTrace();
- } finally{
- try {
- input.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- }
[java] view plain copy
3、Controller
[java] view plain copy
- /**
- * 转到Excel上传页面
- * @return
- * @author lp
- */
- @RequestMapping(value="/read")
- public String addExcel(){
- return "baseInfo/testExcel";
- }
- **
- * 读取Excel数据到数据库
- * @param file
- * @param request
- * @return
- * @throws IOException
- * @author lp
- */
- @RequestMapping(value="/readExcel")
- public ModelAndView readExcel(@RequestParam(value="excelFile") MultipartFile file,
- HttpServletRequest request,HttpSession session) throws IOException{
- ModelAndView mv = new ModelAndView();
- //判断文件是否为空
- if(file == null){
- mv.addObject("msg", "failed");
- mv.setViewName("excel_result");
- return mv;
- }
- String name = file.getOriginalFilename();
- long size = file.getSize();
- if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){
- mv.addObject("msg", "failed");
- mv.setViewName("excel_result");
- return mv;
- }
- //读取Excel数据到List中
- List<ArrayList<String>> list = new ExcelRead().readExcel(file);
- //list中存的就是excel中的数据,可以根据excel中每一列的值转换成你所需要的值(从0开始),如:
- User user = null;
- List<User> liseUser = new ArrayList<User>();
- for(ArrayList<String> arr:list){
- user= new User();
- user.setAuthor(list.get(0));//每一行的第一个单元格
- listUser.add(user);
- }
- if(userService.saveBatchInsert(listUser)){
- mv.addObject("msg", "success");
- }else{
- mv.addObject("msg", "failed");
- }
- mv.setViewName("excel_result");
- return mv;
- }</span></span>
4、jsp
(1)主页面添加“Excel导入”
<a href="javascript:addExcel();"><em>Excel导入</em></a>function addExcel(){var dg = new $.dialog({title:'导入Excel',id:'excel',1000,height:400,iconTitle:false,cover:true,maxBtn:false,xButton:true,resize:false,page:'user/read.html',});dg.ShowDialog();}
(2)导入页面
[html] view plain copy
- <body>
- <form action="readExcel.html" enctype="multipart/form-data" method="post" id="batchAdd" name="batchAdd" target="result" onsubmit="return check();>
- <div style="margin: 30px;">
- <div><input id="excel_file" type="file" name="excelFile" size="50"/>
- </form>
- <iframe name="result" id="result" src="about:blank" frameborder="0" width="0" height="0"></iframe>
- </body>
- </html>
- <script type="text/javascript">
- var dg;
- $(document).ready(function(){
- dg = frameElement.lhgDG;
- dg.addBtn('ok','保存',function(){
- $("#batchAdd").submit();
- this.disabled=true;
- });
- });
- function success(){
- if(dg.curWin.document.forms[0]){
- dg.curWin.document.forms[0].action = dg.curWin.location+"";
- dg.curWin.document.forms[0].submit();
- }else{
- dg.curWin.location.reload();
- }
- dg.cancel();
- }
- function failed(){
- alert("上传失败!");
- }
- </script>
(3)提示页面
[html] view plain copy
- <body>
- <script type="text/javascript">
- var msg = "${msg}";
- if(msg=="success" || msg==""){
- alert("保存成功");
- parent.success();
- }else{
- parent.failed();
- }
- </script>
- </body>
5、service层
service
boolean saveBatchInsert(List<User> listUser);
serviceimpl
@Transactional
public boolean saveBatchInsert(List<User> listUser){
boolean flag = false;
if(listBaseInfo != null){
userMapper.batchInsert(listUser);
flag = true;
}
return flag;
}
6、dao层
void batchInsert(List<User> list);
7、xml(oracle)
[html] view plain copy
- <insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="false" keyProperty="Id">
- insert into baseinfo(ID,Name,Sex,Birth,IdCardNo,Address,Tel,Author,AddDate,Status)
- <foreach collection="list" item="item" index="index" separator="union all">
- (select
- <span style="white-space:pre"> </span>#{item.id,jdbcType=NUMERIC},
- #{item.name,jdbcType=VARCHAR},
- #{item.sex,jdbcType=CHAR},
- #{item.birth,jdbcType=DATE},
- #{item.idCardNo,jdbcType=CHAR},
- #{item.address,jdbcType=VARCHAR},
- #{item.tel,jdbcType=VARCHAR},
- #{item.author,jdbcType=VARCHAR},
- #{item.addDate,jdbcType=DATE},
- #{item.status,jdbcType=CHAR}
- from dual)
- </foreach>
- </insert>