Java中使用Apache POI 解析Excel文件
1.首先在pom.xml文件中注入依赖:
代码如下:
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