String classfile = this.getClass().getResource("/").getPath();
String key = request.getContextPath();
int indexof = classfile.lastIndexOf(key);
String filepath = classfile.substring(0, indexof) + "/upexcel/";
File uploadDir = new File(filepath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
String realpath = "";
// ServletContext ctx = request.getServletContext();// 获取上下文应用
DiskFileItemFactory factory = new DiskFileItemFactory();// 自动导入类 使用工具 commons-fileupload
File repository = new File(filepath); // (File) ctx.getAttribute("javax.servlet.context.tempdir");// 获取临时文件的存储路径
factory.setRepository(repository);// 设置工程对象的仓库
// String basePath = ctx.getRealPath("/res");// 设置存储路径
// System.out.println(basePath);
ServletFileUpload handler = new ServletFileUpload(factory);// 实例化 servletFileupload 上传
handler.setFileSizeMax(1024 * 1024);
try {
List<FileItem> items = handler.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
System.out.print("非文件数据");
} else {
String fileName = new File(item.getName()).getName();
int ivlast = fileName.lastIndexOf(".");
fileName = "x" + System.currentTimeMillis() + fileName.substring(ivlast);
realpath = filepath + fileName;
File storeFile = new File(realpath);
// 在控制台输出文件的上传路径
// System.out.println(filePath);
// realpath=filePath;
// 保存文件到硬盘
try {
item.write(storeFile);
} catch (Exception e) {
realpath = e.getMessage();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
realpath = e.getMessage();
}
List<Map<String, String>> objsList = getExcle(realpath);
int ic = 0;
if (objsList != null) {
ic = objsList.size();
}
JsonObject objjson = new JsonObject();
if (ic > 0) {
Gson gson = new Gson();
objjson.addProperty("count", ic);
if (ic > 0) {
objjson.addProperty("errmesg", "");
objjson.add("webget", gson.toJsonTree(objsList));
}
} else {
objjson.addProperty("count", -1);
objjson.addProperty("errmesg", "表数据出错");
}
response.getWriter().append(objjson.toString());
}
List<Map<String, String>> getExcle(String xlsFilePath) {
List<Map<String, String>> breList = new ArrayList<Map<String, String>>();
InputStream ips;
HSSFWorkbook wb;
try {
String stemString = "";
ips = new FileInputStream(xlsFilePath);
wb = new HSSFWorkbook(ips);
HSSFSheet sheet = wb.getSheetAt(0);
int iccc = 0;
for (Iterator ite = sheet.rowIterator(); ite.hasNext();) {
Map<String, String> matemMap = new HashMap<String, String>();
int irow = 0;
HSSFRow row = (HSSFRow) ite.next();
if (iccc == 0) {
row = (HSSFRow) ite.next();
}
iccc++;
for (Iterator itet = row.cellIterator(); itet.hasNext();) {
irow++;
HSSFCell cell = (HSSFCell) itet.next();
cell.setCellType(1);//强制转化字符串类型
stemString =cell.getRichStringCellValue().toString().trim();
matemMap.put("co" + irow, stemString);
}
breList.add(matemMap);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return breList;
}