zoukankan      html  css  js  c++  java
  • 要求做一个从网页上导入excel

    要求做一个从网页上导入excel,,开始着手去实现它。

    思路很简单:

    1、做一个jsp页面,页面包括浏览文件,提交文件

    2、将excel文件上传到服务器

    3、  服务器对该excel文件进行读出

    4、  将excel文件内容显示到页面上

     

    环境搭建:

    需要准备的包:commons-fileupload-1.2.1.jar & commons-io-1.3.2.jar 这两个包是上传用的

    jxl.jar 这个包是读取excel用的 下载地址 :http://sourceforge.net/projects/jexcelapi/  建议不要用新版本,因为新版本会出现与jdk版本兼容问题,如果运行程序出现问题的时候请切换旧版本。

     

    一、Jsp页面

    注意:1、在jsp页面的form要使用html本身的<form>标记,而不要使用第三方视图开源框架的form标记,例如不要使用strut的<htm:form>。

       2、在<form>的属性里必须加上  ENCTYPE="multipart/form-data"

    1   <h1>导入Excel</h1>
    2 <hr>
    3 <form action="importExcel" method="post" enctype="multipart/form-data">
    4 <input type="file" name="importExcel" id="importExcel">
    5 <input type="submit" value="导入">
    6 </form>

    二、上传excel的Servlet

    注意:1、导入的excel最好用后缀为.xls,如果用.xlsx可能会导不进去。

    2、在调用FileItem的write方法前必须保证文件的存放路径存在否则出现异常。commons fileupload不会自动为你建立不存在的目录。

    3、上传后会对文件进行重命名,以时间为文件名进行命名

      1  public class Import ExcelServlet extends HttpServlet {
    2 //缓冲区域
    3 File tempPathFile;
    4 //默认路径
    5 String uploadTo ="D:\\";
    6 // 支持的文件类型
    7 String[] errorType = { ".xls" };
    8 //格式化日期
    9 SimpleDateFormat format =new SimpleDateFormat("yyyyMMddHHmmssSSS");
    10 @Override
    11 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    12 throws ServletException, IOException
    13 {
    14 req.setCharacterEncoding("utf-8");
    15 resp.setCharacterEncoding("utf-8");
    16 //取得服务器真实路径
    17 uploadTo = req.getSession().getServletContext().getRealPath("\\") +"upload\\";
    18 // Create a factory for disk-based file items
    19 DiskFileItemFactory factory =new DiskFileItemFactory();
    20 // 设置缓冲区大小,这里是4kb
    21 factory.setSizeThreshold(4096);
    22 // 设置缓冲区目录
    23 factory.setRepository(tempPathFile);
    24 // Create a new file upload handler
    25 ServletFileUpload upload =new ServletFileUpload(factory);
    26 // Set overall request size constraint
    27 // 设置最大文件尺寸,这里是4MB
    28 upload.setSizeMax(4*1024*1024);
    29 // 开始读取上传信息
    30 List fileItems =new ArrayList();
    31 try
    32 {
    33 fileItems = upload.parseRequest(req);
    34 }
    35 catch (FileUploadException e1)
    36 {
    37 e1.printStackTrace();
    38 }
    39 // 依次处理每个上传的文件
    40 Iterator iter = fileItems.iterator();
    41 System.out.println("fileItems的大小是"+ fileItems.size());
    42 // 正则匹配,过滤路径取文件名
    43 String regExp =".+\\\\(.+)$";
    44 Pattern p = Pattern.compile(regExp);
    45 while (iter.hasNext())
    46 {
    47 FileItem item = (FileItem) iter.next();
    48 // 忽略其他不是文件域的所有表单信息
    49 System.out.println("正在处理"+ item.getFieldName());
    50 if (!item.isFormField())
    51 {
    52 String name = item.getName();
    53 long size = item.getSize();
    54 if ((name ==null|| name.equals("")) && size ==0)
    55 continue;
    56 Matcher m = p.matcher(name);
    57 boolean result = m.find();
    58 if (result)
    59 {
    60 boolean flag =false;
    61 for (int temp =0; temp < errorType.length; temp++)
    62 {
    63 if(m.group(1).endsWith(errorType[temp]))
    64 {
    65 flag =true;
    66 }
    67 }
    68 if(!flag)
    69 {
    70 System.out.println("上传了不支持的文件类型");
    71 thrownew IOException(name +": wrong type");
    72 }
    73 try {
    74 String fileName = uploadTo + format.format(new Date()) + m.group(1).substring(m.group(1).indexOf("."));
    75 item.write(new File(fileName));
    76 //调用ReadExcel类进行读出excel
    77 ReadExcel.readExcel(fileName, resp.getWriter());
    78 System.out.println(name +"\t\t"+ size);
    79 }
    80 catch (Exception e)
    81 {
    82 e.printStackTrace();
    83 }
    84 }
    85 }
    86 else
    87 {
    88 // 这里添加对不是上传文件表单项的处理
    89 System.out.println("这是一个表单项");
    90 }
    91 }
    92 }
    93 @Override
    94 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    95 {
    96 doGet(req, resp);
    97 }
    98 @Override
    99 public void init() throws ServletException
    100 {
    101 tempPathFile =new File("d:\\temp\\buffer\\");
    102 if (!tempPathFile.exists())
    103 {
    104 tempPathFile.mkdirs();
    105 }
    106 }
    107 }

    三、读出excel文件内容的类

     1   public class ReadExcel 
    2 {
    3 public staticvoid readExcel(String pathname, PrintWriter out)
    4 {
    5 try {
    6 //打开文件
    7 Workbook book = Workbook.getWorkbook(new File(pathname)) ;
    8 //取得第一个sheet
    9 Sheet sheet = book.getSheet(0);
    10 //取得行数
    11 int rows = sheet.getRows();
    12 for(int i =0; i < rows; i++)
    13 {
    14 Cell [] cell = sheet.getRow(i);
    15 for(int j=0; j<cell.length; j++)
    16 {
    17 //getCell(列,行)
    18 System.out.print(sheet.getCell(j, i).getContents());
    19 System.out.print("&nbsp;");
    20 }
    21 System.out.println("<br/>");
    22 }
    23 //关闭文件
    24 book.close();
    25 }
    26 catch (BiffException e)
    27 {
    28 e.printStackTrace();
    29 }
    30 catch (IOException e)
    31 {
    32 e.printStackTrace();
    33 }
    34 }







  • 相关阅读:
    编程实现SQL Server数据库导入导出操作
    C#正则表达式入门
    Winform实现窗体抖动的效果代码
    js获取当前日期,格式为YYYYMMDD
    XML基本知识及其技术指南
    WPF学习心得
    脚本调试
    标题:VS2008简体中文专业版
    使用 XML Schema 定义元素的基本知识2
    C#操作xml文件入门
  • 原文地址:https://www.cnblogs.com/ayan/p/2308042.html
Copyright © 2011-2022 走看看