在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI。其中功能相对POI比较弱一点。但jExcelAPI对中文支持非常好,API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。
jxl.jar可以到http://sourceforge.net/project/showfiles.php?group_id=79926 下载。
使用如下:
搭建环境
将下载后的文件解包,得到jxl.jar,然后和webwork运行所需要的所有包一并放入classpath,安装就完成了。
jsp代码(uploadFile.jsp):
jsp页面其实很简单,就一个input框放在一个form表单里,请注意着色部分:
form标签务必脚上加上enctype="multipart/form-data,
<input type=file name=fileImages />中的file控件name名称需要和
FileUpload.java中的着色部分保持一致,
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="ww" uri="/webwork" %>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Show case</title>
</head>
<body>
<form action="<%=path %>/upload/doUpload.action" method="POST" enctype="multipart/form-data">
upload: <input type="file" name="fileImages">
<input type="submit" name="upload" value="upload">
<form>
</body>
</html>
java代码(FileUpload.java ):
package com;
import java.io.*;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JFileChooser;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.log4j.Logger;
import com.opensymphony.webwork.ServletActionContext;
public class FileUpload extends BaseAction1{
/**
*
*/
private Logger logger = Logger.getLogger(FileUpload.class);
private static final long serialVersionUID = 5943699833329252614L;
// 对应<input type=file name=fileImages />中的file控件name名称
private File[] fileImages;
private File filepath;
// 获取 文件名称 fileImages file 控件上传文件的文件名称;
private String[] fileImagesFileName;
FileInputStream fileIn;
public String path;
public String stringexcle;
int filesize = 0;
public FileInputStream getFileIn() {
return fileIn;
}
public void setFileIn(FileInputStream fileIn) {
this.fileIn = fileIn;
}
public int getFilesize() {
return filesize;
}
public void setFilesize(int filesize) {
this.filesize = filesize;
}
public String doUploadAction() {
File[] newFileImages = FileUtil.renameToFiles(fileImagesFileName,
fileImages);
if (newFileImages != null && newFileImages.length > 0) {
for (File file : newFileImages) {
try {
if (!FileUtil.verifyFile(file, new String[] { "jpg", "gif",
"jpeg", "png" ,"txt","xls"})) {
this.addFieldError("errorimage",
"Error:Invalid File Type");
return "create";
}
} catch (Exception e) {
e.printStackTrace();
}
}
for (File fileImage : newFileImages) {
try {
String imageName = fileImage.getName();
fileIn = new FileInputStream(fileImage);
filesize = fileIn.available();
logger.info("获得文件名称: " + imageName);
logger.info("获得文件大小:" + filesize);
path=getProductFilePath();
FileUtil.saveFile(fileImage, imageName,
getProductFilePath());
stringexcle=readExcel(fileImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return SUCCESS;
}
/**读取Excel文件的内容
* @param file 待读取的文件
* @return
*/
public static String readExcel(File file){
StringBuffer sb = new StringBuffer();
Workbook wb = null;
try {
//构造Workbook(工作薄)对象
wb=Workbook.getWorkbook(file);
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(wb==null)
return null;
//获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了
Sheet[] sheet = wb.getSheets();
if(sheet!=null&&sheet.length>0){
//对每个工作表进行循环
for(int i=0;i<sheet.length;i++){
//得到当前工作表的行数
int rowNum = sheet[i].getRows();
for(int j=0;j<rowNum;j++){
//得到当前行的所有单元格
Cell[] cells = sheet[i].getRow(j);
if(cells.length>0){
//对每个单元格进行循环
for(int k=0;k<cells.length;k++){
//读取当前单元格的值
String cellValue = cells[k].getContents();
sb.append(cellValue+"\t");
}
}
sb.append("\r\n");
}
sb.append("\r\n");
}
}
//最后关闭资源,释放内存
wb.close();
return sb.toString();
}
//得到文件路径
public File getSelectedFile()
{
JFileChooser jfc = new JFileChooser();
int returnVal = jfc.showSaveDialog(null);
//得出文件路径
if(returnVal == JFileChooser.APPROVE_OPTION )
{
System.out.println("The path of the files:"+jfc.getSelectedFile().getName());
}
return jfc.getSelectedFile();
}
public void searchAction(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
PrintWriter out;
String fileImages = ServletActionContext.getRequest().getParameter("fileImages");//从JSP页面拿值
// String[] fileImages=null;
System.out.println(fileImages);
try {
out = ServletActionContext.getResponse().getWriter();
// for(int i=0;i<fileImages.length;i++){
out.println("<input type='file' value='"+fileImages+"' name='uploadFiles'>");
// }
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public File[] getFileImages() {
return fileImages;
}
public void setFileImages(File[] fileImages) {
this.fileImages = fileImages;
}
public String[] getFileImagesFileName() {
return fileImagesFileName;
}
public void setFileImagesFileName(String[] fileImagesFileName) {
this.fileImagesFileName = fileImagesFileName;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public File getFilepath() {
return filepath;
}
public void setFilepath(File filepath) {
this.filepath = filepath;
}
public String getStringexcle() {
return stringexcle;
}
public void setStringexcle(String stringexcle) {
this.stringexcle = stringexcle;
}
}
FileUtil.java :
package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtil {
// 重命名文件;
public static File[] renameToFiles(String[] fileNames, File[] files) {
File[] retFiles = null;
if (fileNames != null && fileNames.length > 0) {
retFiles = new File[fileNames.length];
for (int i = 0, n = fileNames.length; i < n; i++) {
File dist = new File(fileNames[i]);
files[i].renameTo(dist);
retFiles[i] = dist;
}
}
return retFiles;
}
// save文件
public static long saveFile(File file, String fileName, String filePath)
throws Exception {
if (file == null) {
return 0;
}
File filepath = new File(filePath);
if (!filepath.isDirectory())
filepath.mkdirs();
File filedesc = new File(filepath, fileName);
return copyFile(file, filedesc);
}
// copy文件
public static long copyFile(File fromFile, File toFile) {
long len = 0;
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(fromFile);
out = new FileOutputStream(toFile);
byte[] t = new byte[1024];
int ii = 0;
while ((ii = in.read(t)) > 0) {
out.write(t, 0, ii);
len += ii;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return len;
}
// 验证文件正确;
public static boolean verifyFile(File file, String[] exts) throws Exception {
boolean flag = false;
if (file != null) {
String ext = getExtension(file.getName());
if (ext == null) {
return false;
}
if (exts != null && exts.length > 0) {
if (exts[0].equals("*.*"))
return true;
for (int i = 0; i < exts.length; i++) {
if (ext.equalsIgnoreCase(exts[i])) {
flag = true;
break;
}
}
}
}
return flag;
}
// 取得文件扩展;
public static String getExtension(String fileName) {
int newEnd = fileName.length();
int i = fileName.lastIndexOf('.', newEnd);
if (i != -1) {
return fileName.substring(i + 1, newEnd);
} else {
return null;
}
}
}
BaseAction1.java :
package com;
import java.io.File;
import com.opensymphony.xwork.ActionSupport;
public class BaseAction1 extends ActionSupport {
private static final long serialVersionUID = -2796680436059696842L;
private static final String FILE_PATH = "d:/upload/"; // 文件realpath;
public String getProductFilePath() {
File filesPath = new File(FILE_PATH);
if (!filesPath.exists()) { // (canRead()
filesPath.mkdirs(); // mkdirs()
}
return FILE_PATH;
}
}
webwork.properties
# 保存的目录缺省使用 javax.servlet.context.tempdir
webwork.multipart.saveDir= javax.servlet.context.tempdir
webwork.multipart.maxSize=102400000
# 文件上传设置
# 用来处理HTTP POST请求,编码使用MIME-type multipart/form-data方式的
webwork.multipart.parser=jakarta
# 指定locale,编码
webwork.i18n.encoding=UTF-8
webwork.custom.i18n.resources=messages,acl,definition
# 开发模式设定
webwork.devMode = false
# 配置自动更新设定
webwork.configuration.xml.reload=true
# 国际化资源设定
webwork.i18n.reload=true
xwork.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.1.1//EN" "http://www.opensymphony.com/xwork/xwork-1.1.1.dtd">
<xwork>
<include file="webwork-default.xml" />
<!-- 引用多个 xwork_*.xml -->
<include file="xwork_upload.xml" />
</xwork>
xwork_upload.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.1.1//EN" "http://www.opensymphony.com/xwork/xwork-1.1.1.dtd">
<xwork>
<package name="upload" extends="webwork-default" namespace="/upload">
<interceptors>
<interceptor name="upload"
class="com.opensymphony.webwork.interceptor.FileUploadInterceptor">
<param name="maximumSize">10000000</param>
</interceptor>
<interceptor-stack name="uploadStack">
<interceptor-ref name="upload" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="WSStack" />
<action name="doUpload"
class="com.FileUpload" method="doUploadAction">
<interceptor-ref name="params" /><!-- 将请求中的参数设置到Action中去 -->
<interceptor-ref name="basicStack" />
<interceptor-ref name="uploadStack" />
<result name="success">
<param name="location">/success.jsp</param>
</result>
</action>
</package>
</xwork>
success.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="/webwork" prefix="ww" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Showcase</title>
</head>
<body>
<h1>Fileupload sample</h1>
<ul>
<li>ContentType: <ww:property value="filesize" /></li>
<li>FileName: <ww:property value="path" /></li>
<li>File: <ww:property value="filepath" /></li>
</ul>
</body>
</html>