使用maven+springmvc+POI对上传的Excel文件进行解析并操作

来源:互联网 发布:淘宝抢购秒杀快速付款 编辑:程序博客网 时间:2024/05/22 16:07


经过前几篇文章,已经成功把excel文件成功上传成功了,接下来就是要在后台中拿到excel的每一行和每一列进行操作。怎样解析excel文件拿到里面的内容就变得重中之重了,请看我下面的“神来之笔"。

1、pom.xml

<!-- 解析Excel文件的jar包 --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.14</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.14</version></dependency><!-- 解析Excel文件的jar包 -->

2、ImportExcelUtil.java(Excel解析工具类)

/** * *//** * @author congliu * */package ad.web.util;import java.io.IOException;import java.io.InputStream;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;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;public class ImportExcelUtil {private final static String excel2003L = ".xls"; // 2003- 版本的excelprivate final static String excel2007U = ".xlsx"; // 2007+ 版本的excel/** * 描述:获取IO流中的数据,组装成List<List<Object>>对象 *  * @param in,fileName * @return * @throws IOException */public List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception {List<List<Object>> list = null;// 创建Excel工作薄Workbook work = this.getWorkbook(in, fileName);if (null == work) {throw new Exception("创建Excel工作薄为空!");}Sheet sheet = null;Row row = null;Cell cell = null;list = new ArrayList<List<Object>>();// 遍历Excel中所有的sheetfor (int i = 0; i < work.getNumberOfSheets(); i++) {sheet = work.getSheetAt(i);if (sheet == null) {continue;}// 遍历当前sheet中的所有行for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum() + 1; j++) { // 这里的加一是因为下面的循环跳过取第一行表头的数据内容了row = sheet.getRow(j);if (row == null || row.getFirstCellNum() == j) {continue;}// 遍历所有的列List<Object> li = new ArrayList<Object>();for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {cell = row.getCell(y);li.add(this.getCellValue(cell));}list.add(li);}}work.close();return list;}/** * 描述:根据文件后缀,自适应上传文件的版本 *  * @param inStr,fileName * @return * @throws Exception */public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {Workbook wb = null;String fileType = fileName.substring(fileName.lastIndexOf("."));if (excel2003L.equals(fileType)) {wb = new HSSFWorkbook(inStr); // 2003-} else if (excel2007U.equals(fileType)) {wb = new XSSFWorkbook(inStr); // 2007+} else {throw new Exception("解析的文件格式有误!");}return wb;}/** * 描述:对表格中数值进行格式化 *  * @param cell * @return */public Object getCellValue(Cell cell) {Object value = null;DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化DecimalFormat df2 = new DecimalFormat("0.00"); // 格式化数字switch (cell.getCellType()) {case Cell.CELL_TYPE_STRING:value = cell.getRichStringCellValue().getString();break;case Cell.CELL_TYPE_NUMERIC:if ("General".equals(cell.getCellStyle().getDataFormatString())) {value = df.format(cell.getNumericCellValue());} else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {value = sdf.format(cell.getDateCellValue());} else {value = df2.format(cell.getNumericCellValue());}break;case Cell.CELL_TYPE_BOOLEAN:value = cell.getBooleanCellValue();break;case Cell.CELL_TYPE_BLANK:value = "";break;default:break;}return value;}}

3、UploadAndDownAction.java (spring控制器)

package ad.web.action;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.io.FileUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import ad.web.bean.InfoVo;import ad.web.util.ImportExcelUtil;@Controllerpublic class UploadAndDownAction {/** * 上传多个附件的操作类 *  * @param multiRequest * @throws Exception */@RequestMapping(value = "/upload", method = RequestMethod.POST)@ResponseBodypublic String doUploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {if (!file.isEmpty()) {try {// 这里将上传得到的文件保存指定目录下FileUtils.copyInputStreamToFile(file.getInputStream(),new File("d:\\upload\\file\\", System.currentTimeMillis() + file.getOriginalFilename()));} catch (IOException e) {e.printStackTrace();}}InputStream in = null;List<List<Object>> listob = null;in = file.getInputStream();listob = new ImportExcelUtil().getBankListByExcel(in, file.getOriginalFilename());// 该处可调用service相应方法进行数据保存到数据库中,现只对数据输出for (int i = 0; i < listob.size(); i++) {List<Object> lo = listob.get(i);InfoVo vo = new InfoVo();vo.setCode(String.valueOf(lo.get(0)));vo.setName(String.valueOf(lo.get(1)));vo.setDate(String.valueOf(lo.get(2)));vo.setMoney(String.valueOf(lo.get(3)));System.out.println("打印信息-->机构:" + vo.getCode() + "  名称:" + vo.getName() + "   时间:" + vo.getDate() + "   资产:"+ vo.getMoney());}return "success"; // 上传成功则跳转至此success的信息}@RequestMapping("/download")public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {response.setContentType("text/html;charset=UTF-8");BufferedInputStream in = null;BufferedOutputStream out = null;request.setCharacterEncoding("UTF-8");String path = request.getSession().getServletContext().getRealPath("/resources/");String fileName = "template.xlsx";try {File f = new File(path + fileName);response.setContentType("application/x-excel");response.setCharacterEncoding("UTF-8");response.setHeader("Content-Disposition", "attachment; filename=" + fileName);response.setHeader("Content-Length", String.valueOf(f.length()));in = new BufferedInputStream(new FileInputStream(f));out = new BufferedOutputStream(response.getOutputStream());byte[] data = new byte[1024];int len = 0;while (-1 != (len = in.read(data, 0, data.length))) {out.write(data, 0, len);}} catch (Exception e) {e.printStackTrace();} finally {if (in != null) {in.close();}if (out != null) {out.close();}}}}

4、InfoVo.java(保存Excel数据对应的对象)

/** *  *//** * @author congliu * */package ad.web.bean;//将Excel每一行数值转换为对象public class InfoVo {private String code;private String name;private String date;private String money;public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDate() {return date;}public void setDate(String date) {this.date = date;}public String getMoney() {return money;}public void setMoney(String money) {this.money = money;}}

前端就是个上传文件的控件就可以了,可以看前面转载的几篇文章,呵呵。





原创粉丝点击