在使用Java读取和分析Excel文件时,通常是通过组件来完成的,比较常用的包括POI和JExcel,本文简单阐述了如何使用JExcel读入一个Excel文件,当文件读取后,可以做出自己的解析和修改操作,再加修改后的结果发回到JSP页面。
JSP页面:
<% @ page language = " java " import = " java.util.* " pageEncoding = " GBK " %> <% @ page import = " java.lang.* " %> <% @ page import = " java.io.* " %> <% @ page import = " net.hyweb.* " %> <% String temp = " C://TEMP " ; com.sysway.oa.service.tools.Fileupload fileUpload = new com.sysway.oa.service.tools.Fileupload(temp, " /WEB-INF " , request); // 通过检测checkbox的选择情况,确定文件上传路径 if (request.getParameterValues( " ch1 " ) ! = null ){ String [] ch1 = request.getParameterValues( " ch1 " ); if (ch1[ 0 ].equals( " ch1 " )){ System.out.println( " ch1 checked... " ); String des1 = request.getRealPath( " /FinancialReports/excelFile " ); des1 = des1 + " // " ; fileUpload.setDestinationPath(des1); boolean uploadResult1 = fileUpload.Upload( true ); } } %> <% 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 > File upload JavaBean Page </ 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 ="keyword1,keyword2,keyword3" > < meta http-equiv ="description" content ="This is my page" > < LINK HREF ="/res/skin/skycloud/base.css" REL =stylesheet TYPE ="text/css" > < LINK HREF ="/res/skin/skycloud/list.css" REL =stylesheet TYPE ="text/css" > </ head > < body > 文件上传成功 < br > </ body > </ html >
Java文件:
/* * Author: Huang ye(www.hyweb.net) * 代码开源, 引用请注明出处 * * 2005-11-14 * */ package net.hyweb; import java.io.File; import java.io.OutputStream; import jxl.Workbook; public class ExcelConvertor { public ExcelConvertor() { super(); // TODO 自动生成构造函数存根 } /* * * 传入目标xls文件位置,返回读出的excel文件 */ public static void writeExcel(String inputPath, OutputStream os) throws Exception { // A factory method which takes in an excel file and reads in the contents. Workbook inWorkbook = Workbook.getWorkbook( new File(inputPath)); // Creates a writable workbook as a copy of the workbook passed in. jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os, inWorkbook); // 将具体的处理逻辑(针对sheet和cell)放入这里 // 写入Exel工作表 wwb.write(); // 关闭Excel工作薄对象 wwb.close(); System. out .println( " YES! " ); } }