首先说一说个人思路:
- 步骤一:首先将你要导入的Excel做一个文件上传到Tomcat项目目录下。
- 步骤二:读取导入到项目目录下的Excel文件。
- 步骤三:将读取的内容插入到数据库中。
jsp页面代码:
<h4>导入Excel文件</h4>
<form action="importExcel.action" name="ImportForm" enctype="multipart/form-data" method ="post">
<div>
<!-- accept属性限制上传文件的类型-->
<input type="file" id="file" name="file" accept=".xls,.xlsx"/>
<button type="button" class="btn btn-success" onclick="Import()">确定导入</button>
</div>
</form>
<!--js代码 -->
function Import(){
//获取Excel文件名FileNmae,并作为参数跳转
window.ImportForm.action = "importExcel.action?FileName="+document.getElementById("file").value;
window.ImportForm.submit();
alert("导入成功");
}
struts2.xml配置
<action name="importExcel" class="StationAction" method="importExcel">
<result name="success" type="redirect">/station/station.action</result>
<result name="fail">/500.jsp</result>
</action>
Action层代码
/**
* 导入Excel
*/
public String importExcel(){
//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String savePath = ServletActionContext.getServletContext().getRealPath("/excel");
//获取Jsp页面传来的文件虚拟路径,文件上传是,系统会在文件名的前面加上虚拟路径,如:C:/path/example.xls
String FileName = request.getParameter("FileName");
String temp[] = FileName.split("\\\\");
if (temp.length > 1) {
//将反斜杠去除
FileName = temp[temp.length - 1];
}
if(file!=null){
//创建保存在服务器文件,以FileName命名
File savefile = new File(new File(savePath), FileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
try {
FileUtils.copyFile(file, savefile);
} catch (IOException e) {
e.printStackTrace();
}
ActionContext.getContext().put("message", "文件上传成功,正在导入Excel");
}
//获取文件路径
String filePath = savePath+"\\"+FileName;
try {
//导入自己编写的导入Excel工具类
ExcelController ec = new ExcelController(filePath);
//将读取的内容保存在集合中
List<Station> importList = ec.readExcel();
System.out.println("size:"+importList.size());
Iterator<Station> it = importList.iterator();
//获取数据库里的所有场站名
List list = stationService.getAllStationName();
boolean flag = false;
while(it.hasNext()){
Station s = it.next();
//station类
Station station = new Station();
//判断场站名是否有重复值,有就不导入,没有就导入
if(s.getStationName()!=null){
String ss = null;
Iterator iter = list.iterator();
while(iter.hasNext()){
ss = (String) iter.next();
if(s.getStationName().equals(ss)){
flag= false;
break;
}else{
flag = true;
}
}
//flag为true说明场站不存在,导入该条数据
if(flag){
if(s.getCatalog()!=null){
station.setCatalog(s.getCatalog());
}
/*
* ...此处省略你的Excel表格与你数据库的内容相匹配
*/
//保存场站信息到数据,调用Hibernate封装的saveOrUpdate方法
stationService.saveStation(station);
}else{
ActionContext.getContext().put("message", "场站名称不能为空");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
ActionContext.getContext().put("message", "导入成功");
return "success";
}
Excel工具类 ExcelController,需导入POI jar包
public class ExcelController{
private XSSFWorkbook xssfWB = null;
private HSSFWorkbook hssfWB = null;
InputStream read = null;
OutputStream write = null;
private String file;
public ExcelController(){}
/**
* 初始化文件,判断文件情况
* 找到合适的类型控制
* @param file
* @throws Exception
*/
public ExcelController(String file) throws Exception{
this.file = file;
read = null;
if(file==null||"".equals(file)){
System.out.println("文件不能为空!");
throw new Exception();
}
try {
read = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println("文件路径不正确!");
e.printStackTrace();
}
try{
if(file.endsWith(".xls")){
hssfWB = new HSSFWorkbook(read);
}else if(file.endsWith(".xlsx")){
xssfWB = new XSSFWorkbook(read);
}else{
System.out.println("文件格式不正确!");
throw new IOException();
}
}catch(IOException e){
System.out.println("文件已损坏或者未知原因!");
e.printStackTrace();
}
}
/**
* 读取Excel;
* @return
*/
public List<Station> readExcel(){
List<Station> list = null;
if(xssfWB!=null){
list = this.read2007Excel();
}else if(hssfWB!=null){
list = this.read2003Excel();
}
this.free();
return list;
}
/**
* 释放IO流
* 减少内存损耗
*/
private void free(){
try{
if(read!=null){
read.close();
}
if(write!=null){
write.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
/**
* 私有化读取2007以上版本Excel
* @return
*/
private List<Station> read2007Excel(){
List<Station> list = new ArrayList<Station>();
//获取表里的第一个工作蒲
XSSFSheet sheet = xssfWB.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
if(sheet.getPhysicalNumberOfRows()>0){
//从Excel表格第1行开始读取
for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
row = sheet.getRow(i);
System.out.println("row:"+row.getRowNum());
if(row==null){
continue;
}
int j=0;
cell = row.getCell(j++);
System.out.println("cellType:"+cell.getCellType());
String catalog1 = (String)getCellValue(cell);
System.out.println("catalog:"+catalog1);
/*
*此处也可读取更多属性
*/
list.add(new Station(catalog1);
}
}else{
System.out.println("文件中没有数据!");
}
return list;
}
/**
* 私有化读取2007版本以下Excel
* @return
*/
private List<Station> read2003Excel(){
List<Station> list = new ArrayList<Station>();
//获取表里的第一个工作蒲
HSSFSheet sheet = hssfWB.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
System.out.println("sheetRows:"+sheet.getPhysicalNumberOfRows());
if(sheet.getPhysicalNumberOfRows()>0){
//从Excel表格第1行开始读取
for(int i=1;i<sheet.getPhysicalNumberOfRows();i++){
row = sheet.getRow(i);
System.out.println("row:"+row.getRowNum());
if(row==null){
continue;
}
int j=0;
cell = row.getCell(j++);
System.out.println("cellType:"+cell.getCellType());
String catalog1 = (String)getCellValue(cell);
System.out.println("catalog:"+catalog1);
list.add(new Station(catalog1);
}
}else{
System.out.println("文件中没有数据!");
}
return list;
}
/**
* 获取单元格格式
*/
private static Object getCellValue(Cell cell) {
Object obj = null;
if(cell == null) return null;
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
obj = cell.getRichStringCellValue().getString().trim();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
obj = cell.getDateCellValue();
}else {
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
obj = nf.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
obj = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
obj = cell.getCellFormula();
break;
default:
}
return obj;
}
到这里已经可以实现将Excel里的内容导入到数据库中了