Java解析Excel文件(导入)

Java中使用Apache POI 解析Excel文件

1.首先在pom.xml文件中注入依赖:

代码如下:

<dependency>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi</artifactId>
       <version>3.14</version>
</dependency>

<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>3.14</version>
</dependency>
<dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.14</version>
 </dependency>

2.在项目中创建一个测试类,本案例路径为:

3.按照需求制作导入模板(本案例模板如下):

每一个Excel文件都将被解析成一个WorkBook对象; 
Excel中的每一页都将被解析成一个Sheet对象; 
Excel中的每一行都是一个Row对象, 
Excel中的每一个单元格都是一个Cell对象。

4.下面我们在创建的测试类中写测试模板导入功能代码。

4.1需要引入的包:

4.2 下面按环节展示,代码在文章末尾处展示:

5.启动项目,测试接口:

在本案例中,文件是从文件服务器中获取的。所以将填好的模板已经上传至服务器中。

路径为:http://file.gcx365.com:8090/group1/M00/01/ED/d1ozt1tr0reAGTC2AAAmVz8gJ_Q22.xlsx

浏览器中调用本地接口:

http://localhost:8080/test/sgmTestController/importFile.do?url=http://file.gcx365.com:8090/group1/M00/01/ED/d1ozt1tr0reAGTC2AAAmVz8gJ_Q22.xlsx

页面返回结果:导入成功。

下面我们去数据库中查看数据是否已经成功导入到数据库中。

数据导入成功。

源码如下:

package com.gcx.test.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gcx.test.model.SgmTest;
import com.gcx.test.service.SgmTestService;
import com.gcx.test.service.util.MyResult;

/** 
 * @author sunguimin
 * @version 创建时间:2018-08-01 17:57:28 
 */
@Controller
@RequestMapping("sgmTestController")
public class SgmTestController {

    @Autowired
    SgmTestService sgmTestService;
    
    
    //模板导入
    @RequestMapping("/importFile")
    @ResponseBody
    public ModelMap importFile(HttpServletRequest request, HttpServletResponse response,String url)throws IllegalStateException, IOException {
        //传入文件地址url
        ModelMap  model=new ModelMap();
        String fileType = url.substring(url.lastIndexOf(".") + 1, url.length());//截取文件类型
        
        String str = request.getSession().getServletContext().getRealPath("/"); //获取项目的绝对路径
        
        str = str +"/WEB-INF/classes/"+url.substring(url.lastIndexOf("/"));//Excel模板所在的路径。
        model.addAttribute("result", "导入成功");
        
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try
        {
            urlfile = new URL(url);
            httpUrl = (HttpURLConnection)urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(str));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1)
            {
                bos.write(b, 0, len);
            }
            System.out.println("上传成功");
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bis.close();
                bos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        
        
        InputStream stream = new FileInputStream(str);
        Workbook wb = null;
        if (fileType.equals("xls")) {
            wb = new HSSFWorkbook(stream);
        } else if (fileType.equals("xlsx")) {
            wb = new XSSFWorkbook(stream);
        } else {
            model.addAttribute("result", "您输入的excel格式不正确");
            return model;
        }
        //得到sheet1模板
        Sheet sheet1 = wb.getSheetAt(0);
        // 得到Excel的行数
         int totalRows = sheet1.getPhysicalNumberOfRows();
         //拿到sheet的名称
         String sheetname = sheet1.getSheetName();
         //判断sheet的名称是否正确
         if(!"新闻内容导入模板".equals(sheetname)){
             model.addAttribute("result", "您输入的excel格式不正确");
             return model;
         }
         int totalCells = 0;
         // 得到Excel的列数(前提是有行数)
         if (totalRows > 1 && sheet1.getRow(0) != null) {
             totalCells = sheet1.getRow(0).getPhysicalNumberOfCells();
         }
         
         SgmTest record = new SgmTest();//定义对象
         MyResult<Object> result = null;
         try {
             //sheet1表
             /*
              * sheet.getPhysicalNumberOfRows():返回物理定义的行数(不是工作表中的行数) 
              * sheet.getLastRowNum():返回此sheet中最后一行的数字编号,base 0 
              * */
             if(sheet1.getLastRowNum() == 0 && sheet1.getPhysicalNumberOfRows() == 0 ){
                    model.addAttribute("result", "您的excel格式为空");
                    return model;
             }else{
                for (int r = 3; r < totalRows; r++) {//模板中第四行开始才是用户填写的数据,所以r=3
                     Row row = sheet1.getRow(r);    
                     
                     //这个地方判断用户录入的数据是否为空,选择一个必填的字段,如果该表格内容为空,那么说明该条数据无效。
                     if(row.getCell(0) == null || String.valueOf(row.getCell(0)).equals("")){
                         return model;
                     }
                     //第一列
                     record.setTitle(String.valueOf(row.getCell(0) == null?"":row.getCell(0)));//插入标题
                     //第二列
                     if(row.getCell(1).getCellType()==0){//获取Date时间格式
                            if (HSSFDateUtil.isCellDateFormatted(row.getCell(1))) { //Excel Date类型处理
                                Date date = HSSFDateUtil.getJavaDate(row.getCell(1).getNumericCellValue());   
                                record.setSjfsTime(date);
                            }
                        }
                     //第三列
                     record.setProvince(String.valueOf(row.getCell(2) == null?"":row.getCell(2)));
                     //第四列
                     record.setCity(String.valueOf(row.getCell(3) == null?"":row.getCell(3)));
                     //第五列
                     record.setType(String.valueOf(row.getCell(4) == null?"":row.getCell(4)));
                     //第六列
                     record.setClassify(String.valueOf(row.getCell(5) == null?"":row.getCell(5)));
                     //第七列
                     record.setLaiyuan(String.valueOf(row.getCell(6) == null?"":row.getCell(6)));
                     //第八列
                     record.setContent(String.valueOf(row.getCell(7) == null?"":row.getCell(7)));
                     record.setInsertTime(new Date());//插入新增时间
                     sgmTestService.addRecord(request, response, record);
                 }
            }
        } catch (Exception e) {
            model.addAttribute("result", e.getMessage());
        }finally{
            return model;
        }
    }
}
 

猜你喜欢

转载自blog.csdn.net/Soulmate_Min/article/details/81534709
今日推荐