首先说一下所使用的POI版本3.8,需要用的的Jar包:

dom4j-1.6.1.jar
poi-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
poi-scratchpad-3.8-20120326.jar
xmlbeans-2.3.0.jar

web前端页面:

action:填写请求地址;

enctype="multipart/form-data":一定要带上,要不然后台获取不到文件的字节流;

<form id="AddForm" action="excel/fileInfo.do" method="post" enctype="multipart/form-data"> 
  <input id="excel" type="file" name="excel" /> <br />
  <input onclick="submitFile()" type="button" value="提交" />
</form>

struts2的请求配置:

<package name="drugs" extends="struts-default" namespace="/drugs">
  <action name="fileInfo" class="com.daat.manager.drugs.web.actions.DrugsAction" method="fileInfo">
  <result name="success" type="jsonResult"></result>
</action>
</packge>

java处理struts2请求:

 import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.ServletActionContext; public class DrugsAction extends ActionSupport{
  private File excelFile;
private String excelFileFileName; public File getExcelFile() {
return excelFile;
} public void setExcelFile(File excelFile) {
this.excelFile = excelFile;
} public String getExcelFileFileName() {
return excelFileFileName;
} public void setExcelFileFileName(String excelFileFileName) {
this.excelFileFileName = excelFileFileName;
}   
public String fileInfo(){
try {
//创建新文件名
String excelName = "xinwenjian";
//获取文件上传路径
String filePath = getFilePath(excelFileName1);
//文件复制后保存路径
String path="WEB-INF/upload/";
//根据相对部署路径计算完整路径
path=ServletActionContext.getServletContext().getRealPath(path);
System.out.println(path);
String sufix = FileUtil.getFileSufix(excelFileFileName).toLowerCase();
excelFileName1 = excelFileName1 + "." + sufix;
//判断上传文件的保存目录是否存在
if (!file.exists() && !file.isDirectory()) {
//创建目录
file.mkdir();
}
//复制文件到服务器
FileUtils.copyFile(excelFile,new File(path,excelFileName1));
//解析excel文件
allInfo(path,excelFileName1);
} catch (IOException e) {
System.out.println("error");
e.printStackTrace();
}
//this.outJsonString("success");
return getResult();
}

/**
* 获取文件上传路径
* @param dirpath
* @return
*/
public static String getFilePath(String fileName) {
System.out.print(fileName);
String filePath = fileName.substring(0, 2)+File.separator+fileName.substring(2, 4)+File.separator
+fileName.substring(4, 6)+File.separator;
return filePath;
}

}

解析Excel类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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.ss.usermodel.WorkbookFactory; public class UserInfo { public static void main(String[] args){
String path2003 = "D:\\Users\\star\\Workspaces\\MyEclipse 10\\.metadata\\.me_tcat\\webapps\\dms\\WEB-INF";
String FileName="xinwenjian.xls";
              //解析文件
excelInfo(path2003,FileName);
              //删除文件
deleteFile(path2003,FileName);
} public static List excelInfo(String path,String FileName){
long start2003 = System.currentTimeMillis();
List excellist=new ArrayList();
String path2003 = "";//Excel2003文件路径 //解析Excel
excellist = parseExcel(path+File.separator+FileName);
System.out.println(excellist.size());
System.out.println("excellist"+excellist.toString());
System.out.println("size:"+excellist.size());
long end2003 = System.currentTimeMillis();
System.out.println("解析Excel2003完毕!共用时"+(end2003-start2003)+"毫秒!");
deleteFile(path,FileName);
return excellist;
} /**
* 根据路径加载解析Excel
* @param path
* @return
*/
public static List parseExcel(String path){
List excellist=new ArrayList();
System.out.println(path);
Map map = new HashMap();
File file = null;
InputStream input = null;
Workbook workBook = null;
Sheet sheet = null;
if(path!=null&&path.length()>7){
//判断文件是否是Excel(2003、2007)
String suffix = path.substring(path.lastIndexOf("."),path.length());
if (".xls".equals(suffix) || ".xlsx".equals(suffix)) {// 2003后缀或2007后缀
file = new File(path);
try {
input = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println("未找到指定的文件!");
e.printStackTrace();
} catch (Exception e) {
System.out.println("读取Excel文件发生异常!");
e.printStackTrace();
}
if(!input.markSupported()){
input = new PushbackInputStream(input,8);
}
try{
if(POIFSFileSystem.hasPOIFSHeader(input) || POIXMLDocument.hasOOXMLHeader(input)){
workBook = WorkbookFactory.create(input);
}else{
System.out.println("非法的输入流:当前输入流非OLE2流或OOXML流!");
}
} catch(IOException e){
System.out.println("创建表格工作簿对象发生IO异常!原因:"+e.getMessage());
e.printStackTrace();
} catch(InvalidFormatException e){
//Your InputStream was neither an OLE2 stream, nor an OOXML stream.
System.out.println("非法的输入流:当前输入流非OLE2流或OOXML流!");
e.printStackTrace();
}
try{
if(workBook!=null){
int numberSheet = workBook.getNumberOfSheets();
if(numberSheet>0){
sheet = workBook.getSheetAt(0);//获取第一个工作簿(Sheet)的内容【注意根据实际需要进行修改】
excellist = getExcelContent(sheet);
}else{
System.out.println("目标表格工作簿(Sheet)数目为0!");
}
}
input.close();
}catch(IOException e){
System.out.println("关闭输入流异常!"+e.getMessage());
e.printStackTrace();
}
}else{
System.out.println("非法的Excel文件后缀!");
}
}else{
System.out.println("非法的文件路径!");
}
return excellist;
} /**
* 解析(读取)Excel内容
* @param sheet
* @return
*/
@SuppressWarnings("static-access")
public static List getExcelContent(Sheet sheet){
List excellist=new ArrayList(); Date data=new Date();
int rowCount = sheet.getPhysicalNumberOfRows();//总行数
if(rowCount>1){
Row titleRow = sheet.getRow(2);//标题行
int columnNum=titleRow.getPhysicalNumberOfCells();//总列数
for(int i=3;i<rowCount-1;i++){//遍历行,略过标题行,从第二行开始
Row row = sheet.getRow(i);//第i行
Map map=new HashMap();
for(int j=1;j<columnNum;j++){
Cell cell = row.getCell(j);//列
String title=titleRow.getCell(j).getStringCellValue();//标题
Object conten=isNUMERICAndSTRING(cell);
//当读取到null时不会报错,继续执行
                 if("NaN".equals(conten)){
conten=" ";
}
                 //string类型
if(title.indexOf("架位号")>=0){
map.put("shelfNum",conten);
}
                 //数字类型
else if(title.indexOf("商品类型")>=0){
map.put("drugType", (int)cell.getNumericCellValue());
}
//判断日期类型
else if(titleRow.getCell(j).getStringCellValue().indexOf("入库日期")>=0){
if(HSSFDateUtil.isCellDateFormatted(cell)){
data=cell.getDateCellValue();
map.put("storageDate", data);
}
}
}
excellist.add(map);
System.out.println("第"+i+"行"+excellist.toString());
}
}
return excellist;
}
     //判断行内值的类型
public static Object isNUMERICAndSTRING(Cell cell){
if(cell==null ){
return "NaN";
}else if(cell.getCellType()==cell.CELL_TYPE_STRING){
return cell.getStringCellValue().trim();
}else if(cell.getCellType()==cell.CELL_TYPE_NUMERIC){
return cell.getNumericCellValue();
}
return "error";
}
      //删除文件
private static void deleteFile(String path,String FileName) {
File file = new File(path);
File Array[] = file.listFiles();
for (File f : Array) {
if (f.isFile()) {// 如果是文件
if (f.getName().equals(FileName)) {
f.delete();
return;
}
}
}
} }

  

POI上传,导入excel文件到服务器1的更多相关文章

  1. .NET 客户端上传本地excel文件到服务器上,并在客户端显示

    // 上传按钮 protected void btnUp_Click(object sender, EventArgs e) { bool b = Upload(fuExcel); // 上传exce ...

  2. 前端js webuploader上传(导入)excel文件

    项目开发中用到导入(上传)Excel文件 我使用的是百度的webuploader: 1:下载:http://fex.baidu.com/webuploader/(官方下载/示例) 2:使用Web Up ...

  3. Apache POI 一键上传(导入excel文件到数据库)

    import cn.XXXX.bos.utils.PinYin4jUtils; import org.apache.commons.lang3.StringUtils; // HSSF:操作07版本之 ...

  4. ci框架读取上传的excel文件数据

    原文链接: https://blog.csdn.net/qq_38148394/article/details/87921373 此功能实现使用到PHPExcel类库,PHPExcel是一个PHP类库 ...

  5. java 解析上传的Excel文件

    java poi解析上传的Excel文件 package com.zhl.push.Utils; /** * @Author TAO * @ClassName ExcelData * @Descrip ...

  6. 上传读取Excel文件数据

    /// <summary> /// 上传读取Excel文件数据 /// 来自http://www.cnblogs.com/cielwater /// </summary> // ...

  7. 利用django如何解析用户上传的excel文件

    https://www.jb51.net/article/119452.htm 前言 我们在工作中的时候,会有这种需求:用户上传一个格式固定excel表格到网站上,然后程序负债解析内容并进行处理.我最 ...

  8. 使用ASP.NET上传多个文件到服务器

    在Email系统中经常会上传多个文件到服务器,用户大多习惯一次上传所有的文件,而不是逐个上传,我们可以使用javascript动态地添加file元素到表单,然后在服务器端处理这些file 效果图如下: ...

  9. springMVC从上传的Excel文件中读取数据

    示例:导入客户文件(Excle文件) 一.编辑customer.xlsx 二.在spring的xml文件设置上传文件大小 <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1 ...

随机推荐

  1. fsck命令详解

    基础命令学习目录首页 本文出自 “airfish2000” 博客,更多命令查看博客: http://airfish2000.blog.51cto.com/10829608/1880801   fsck ...

  2. unset命令详解

    基础命令学习目录首页 功能说明:unset是一个内建的Unix shell命令,在Bourne shell家族(sh.ksh.bash等)和C shell家族(csh.tcsh等)都有实现.它可以取消 ...

  3. git push remote: User permission denied

    这种错误因为本地保存了一个错误的账号密码,只需要重新编辑成正确的账号密码 直接上方法

  4. Notes of Daily Scrum Meeting(11.8)

    Notes of Daily Scrum Meeting(11.8) 预备中开始写代码的第一天,因为大家对Android编程的熟悉程度还是不够,所以工程进行的非常缓慢,有四名队员 开始编写自己的任务, ...

  5. bing词典

    一.bug寻找 bug1:点击单词挑战之后选择四级词汇,然后一直狂击答案,点到一个时候就会出现一个情况:不管点击哪一个选项都不会跳至下一题,而且屏幕上方的已做题目数 x/20中的x会乱跳. bug2: ...

  6. 团队冲刺——Five

    昨天: 司宇航:web项目如何部署到公网,把网址做成桌面图标链接,登录记住密码功能. 王金萱:注册和登录界面,用户数据库的信息录入. 马佳慧:做界面. 季方:处理爬虫数据,实现统计功能. 遇到的问题: ...

  7. 剑指offer:替换空格

    题目描述: 请实现一个函数,将一个字符串中的每个空格替换成“%20”.例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy. 思路: 一开始没理解,函数中 ...

  8. week4b:个人博客作业

    下面是week4做程序的过程. 1.在做之前先做客户需求,要求使用的使用mul图. 自己第一次听到这个名字,网上查UML为, http://www.cnblogs.com/wangkangluo1/a ...

  9. ssh结合使用

    springxml配置 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi=& ...

  10. Enterprise Library 3.1 参考源码索引

    http://www.projky.com/entlib/3.1/Microsoft/Practices/EnterpriseLibrary/AppSettings/Configuration/Des ...