利用POI读取Excel数据,实现同时读取多个Excel文件,兼容所有浏览器

                                                                                         

                                                     POI读取多个Excel数据

1、利用POI读取Excel数据,实现同时读取多个Excel文件,兼容所有浏览器。

2、实现过程: 客户端上传多个Excel文件到服务器,服务器读取数据后返回到客户端。

3、亮点:实现多个Excel文件上传,并判断文件类型是否正确和文件是否选择、servlet+poi+jsp、兼容所有浏览器、POI读取Excel技术列子简单易懂

4、理论东东就不多说了,直接看代码,代码直接复制就可以用了。       技术QQ群: 180258862  

5、servlet代码:



import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


public class XlsImport extends HttpServlet {


public XlsImport() {
super();
}


public void destroy() {
super.destroy();
}


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
       doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
try{
Iterator<FileItem> it =  getUPFiles(request) ;
while (it.hasNext()) {
FileItem item = it.next();
if(item!=null && !item.isFormField() && item.getSize()>0){
InputStream f = item.getInputStream();
out.println(importExcle(f));
}
}




out.flush();
out.close();
}catch (Exception e) {
e.printStackTrace();
}
}




public void init() throws ServletException {
// Put your code here
}
public String importExcle(InputStream in) {
StringBuffer buf = new StringBuffer();
try {
int beginRowIndex = 0;// 从excel 中开始读取的起始行数
int totalRows = 0;// 从excel 表的总行数
// 根据文件的输入流,创建对Excel 工作薄文件的引用
HSSFWorkbook workbook = new HSSFWorkbook(in);
// 默认exce的书页是“sheet1”
HSSFSheet sheet = workbook.getSheetAt(0);
// 得到该excel 表的总行数
totalRows = sheet.getLastRowNum();
System.out.println("xls总行数"+sheet.getLastRowNum());
// 循环读取excel表格的每行记录,并逐行进行保存
for (int i = beginRowIndex; i <= totalRows; i++) {
HSSFRow row = sheet.getRow(i);
// 获取一行每列的数据
HSSFCell num0 = row.getCell((short) 0);
HSSFCell num1 = row.getCell((short) 1);
HSSFCell num2 = row.getCell((short) 2);
HSSFCell num3 = row.getCell((short) 3);
// 将数据赋给相关的变量
String str0 = num0.getRichStringCellValue().getString().trim();
String str1 = num1.getRichStringCellValue().getString().trim();
String str2 = num2.getRichStringCellValue().getString().trim();
String str3 = num3.getRichStringCellValue().getString().trim();
System.out.println(str0+"-->"+str1+"-->"+str2+"-->"+str3);
buf.append(str0+"-->"+str1+"-->"+str2+"-->"+str3);
}
return buf.toString();
} catch (Exception e) {
e.printStackTrace();
return e.fillInStackTrace().toString();
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取上传的文件集合
* @param request
* @return
* @throws FileUploadException
*/
public static  Iterator<FileItem> getUPFiles(HttpServletRequest request) throws FileUploadException{
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
return upload.parseRequest(request).iterator(); 
}


}


6、jsp代码|:


<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Excel技术:2013年2月26日</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="Excel技术:2013年2月26日">
<meta http-equiv="description" content="Excel技术:2013年2月26日">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->


  </head>
  <script type="text/javascript" src="<%=basePath%>js/jquery-1.7.2.min.js"></script>
  <script type="text/javascript">
  
  function getXlsFile(){
     $("#btn_import").attr('disabled',true);
     $("#btn_import").val("正在执行......");
            var xls = $("input[name='xlsfile']").val();
            var isfile = 0;
            var count = 0;
        $("input[name='xlsfile']").each(function(){ 
                  //判断文件类型是否正确
                   if($(this).val()=="" || ($(this).val().lastIndexOf(".xls")>-1 ||$(this).val().lastIndexOf(".xlsx")>-1)) { 
                   } else{
                      isfile=1;
                   }
                   //是否至少存在一个文件
                   if($(this).val()!="" && count==0){
                   count++;
                   }
                   
           }); 
          if(isfile==0 && count!=0 ){
              $("#form1").submit();
          }else if(count==0){
            alert("至少要选择一个文件");
          }
          else{
         alert("文件格式不正确,请选择xls、xlsx格式文件.");
             }
          $("#btn_import").attr('disabled',false);
     $("#btn_import").val("确认导入");
 }
  </script>
  <body> 
  <form action="<%=basePath%>poi/xlsimport" method="post" id="form1" enctype="multipart/form-data">
  <pre>
      <input type="file" id="xlsfile" name="xlsfile" class="xls" />
       <input type="file" id="xlsfiles" name="xlsfile" class="xls" />
      <input type="button" value="确认导入" id="btn_import" οnclick="getXlsFile()"/> 
  </pre></form> 

  </body>
</html>


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sencerity

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值