步骤:
1、首先在ftl页面上添加导入按钮跳转到导入详情页面,再写一个导入详情页面sp_importfile.ftl
2、然后在Action中导入一堆包,excel的,reader的,并写excel导入的方法importfile(),设置上传文件的路径uploadFile,开启新的线程处理SP厂商信息,利用SpReader与ExcelReaderUtil导入厂商信息
3、在SpReader.java中写getRows()的方法,获取service,若第一行为标题行,则直接跳过,若第一行直接开始信息就不跳过,然后读取excel中的每条数据,存入实体表中。
下面以SP厂商为例。
excel导入的代码:
// excel导入
public String importfile() {
return "importfile";
}
public String importfilesave()
{
if (excel == null) {
addActionError("请导入excel");
return ERROR;
}
try {
String filePath = FileUtil.copyFile(
ServletActionContext.getServletContext(),
excel,
excelFileName.substring(excelFileName.lastIndexOf(".")+1, excelFileName.length()));
String newfilePath = Tools.class.getClassLoader().getResource("/").getPath();
newfilePath = newfilePath.substring(0, newfilePath.indexOf("/WEB-INF/classes"));
final String finalPath = newfilePath + filePath;
File uploadFile = new File(finalPath);
String excelFilePath = CommonConstant.FTP.READ_FTP_FILE_PATH_FOR_EXCEL + "/" + uploadFile.getName();
System.out.println(excelFilePath);
// 开启新的线程处理入库
new Thread() {
public void run() {
try {
// 执行处理
// 导入SP厂商信息
SpReader reader = new SpReader();
String path = finalPath;
ExcelReaderUtil.readExcel(reader, path);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return ERROR;
}
redirectUrl = "sp!list.action";
return SUCCESS;
}
下面是SpReader的代码:
public class SpReader implements IRowReader {
private static Integer count = 1;
/*
* 业务逻辑实现方法
*
* @see com.eprosun.util.excel.IRowReader#getRows(int, int, java.util.List)
*/
public void getRows(int sheetIndex, int curRow, List<Integer> collist, List<String> rowlist) {
// 获取service
SpService spService = (SpService) SpringUtil
.getBean("spServiceImpl");
// 若第一行为标题行,则直接跳过
if (curRow == 0) {
return;
}
try {
// 处理空值列
rowlist = operateEmptyCol(collist,rowlist);
Sp sp = new Sp(); //一定要每条记录就new一次
sp.setName(rowlist.get(0));
spService.save(sp);
} catch (Exception e) {
e.printStackTrace();
}
}
// 处理空值列
private List<String> operateEmptyCol(List<Integer> collist, List<String> rowlist){
// 转化行数据,将空值填入
List<String> newList = new ArrayList<String>();
// 根据excel的列数初始化
for(int i = 0; i < count; i++){
newList.add("");
}
// 根据有值的列覆盖list
for(int i = 0; i < collist.size(); i++){
newList.set(collist.get(i), rowlist.get(i));
}
return newList;
}
}