JSP导入EXCEL样式

http://demo.gcpowertools.com.cn/spreadjs/exceliosample/exceliosample/

Java实现导入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标记,例如不要使用strut的。

   2、在

的属性里必须加上  ENCTYPE="multipart/form-data"

 <</SPAN>h1>导入Excel</</SPAN>h1>
 <</SPAN>hr>
 <</SPAN>form action="importExcel" method="post" enctype="multipart/form-data">
 <</SPAN>input type="file" name="importExcel" id="importExcel">
 <</SPAN>input type="submit" value="导入"> 
 </</SPAN>form>

二、上传excel的Servlet

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

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

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

public class ImportExcelServlet extends HttpServlet {

//缓冲区域

File tempPathFile;

//默认路径

String uploadTo = "D:\\";

// 支持的文件类型

String[] errorType = { ".xls" };

//格式化日期

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

req.setCharacterEncoding("utf-8");

resp.setCharacterEncoding("utf-8");

//取得服务器真实路径

uploadTo = req.getSession().getServletContext().getRealPath("\\") + "upload\\";

// Create a factory for disk-based file items

DiskFileItemFactory factory = new DiskFileItemFactory();

// 设置缓冲区大小,这里是4kb

factory.setSizeThreshold(4096);

// 设置缓冲区目录

factory.setRepository(tempPathFile);

// Create a new file upload handler

ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint

// 设置最大文件尺寸,这里是4MB

upload.setSizeMax(4*1024*1024);

// 开始读取上传信息

List fileItems = new ArrayList();

try {

fileItems = upload.parseRequest(req);

} catch (FileUploadException e1) {

e1.printStackTrace();

}

// 依次处理每个上传的文件

Iterator iter = fileItems.iterator();

System.out.println("fileItems的大小是" + fileItems.size());

// 正则匹配,过滤路径取文件名

String regExp = ".+\\\\(.+)$";

Pattern p = Pattern.compile(regExp);

while (iter.hasNext()) {

FileItem item = (FileItem) iter.next();

// 忽略其他不是文件域的所有表单信息

System.out.println("正在处理" + item.getFieldName());

if (!item.isFormField()) {

String name = item.getName();

long size = item.getSize();

if ((name == null || name.equals("")) && size == 0)

continue;

Matcher m = p.matcher(name);

boolean result = m.find();

if (result) {

boolean flag = false;

for (int temp = 0; temp < errorType.length; temp++) {

if(m.group(1).endsWith(errorType[temp])) {

flag = true;

}

}

if(!flag) {

System.out.println("上传了不支持的文件类型");

throw new IOException(name + ": wrong type");

}

try {

String fileName = uploadTo + format.format(new Date()) + m.group(1).substring(m.group(1).indexOf("."));

item.write(new File(fileName));

//调用ReadExcel类进行读出excel

ReadExcel.readExcel(fileName, resp.getWriter());

System.out.println(name + "\t\t" + size);

} catch (Exception e) {

e.printStackTrace();

}

}

} else {

// 这里添加对不是上传文件表单项的处理

System.out.println("这是一个表单项");

}

}

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

doGet(req, resp);

}

@Override

public void init() throws ServletException {

tempPathFile = new File("d:\\temp\\buffer\\");

if (!tempPathFile.exists()) {

tempPathFile.mkdirs();

}

}

}

三、读出excel文件内容的类

public class ReadExcel {

public static void readExcel(String pathname, PrintWriter out) {

try {

//打开文件

Workbook book = Workbook.getWorkbook(new File(pathname)) ;

//取得第一个sheet

Sheet sheet = book.getSheet(0);

//取得行数

int rows = sheet.getRows();

for(int i = 0; i < rows; i++) {

Cell [] cell = sheet.getRow(i);

for(int j=0; j

//getCell(列,行)

out.print(sheet.getCell(j, i).getContents());

out.print(" ");

}

out.println("
");

}

//关闭文件

book.close();

} catch (BiffException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

总结:上面只是一个很简单的导入excel文件的例子,如果想做完善还得下更多的功夫。在做的过程中如果出现Workbook打不开,请更换jxl版本,尽量用低版本,这样与jdk兼容会好点

上一篇:java异常(4)


下一篇:【基础篇】关于Java异常机制,看这篇就够了!!