java 读取 excel

在前几天的时候,我写过导出excel的文章,其实都是非常简单的例子。我的博客主要是记录一些非常小、比较实用的例子,因为我本身也只是一个java菜鸟,只能写一些比较肤浅的东西……….好了,废话不多说,现在再说一下excel导入的问题。说是导入,其实就是读取excel的内容,再根据自己的需求来处理读取之后的数据。

这里的例子是:前台一个form,里面有个type为file的input,提交form之后,在后台里面读取file中的excel。这里需要poi的jar包。(下载地址:http://download.csdn.net/detail/wangkaichenjuan/4856657)

前台jsp代码:

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript">$(function() {$("#insetButton").click(function() {$('#excelInsetForm').submit();});});</script></head><body><form id="excelInsetForm" action="readExcel.do" method="post" enctype="multipart/form-data"><input type="file" name="fileName" id="fileName" /><br />    <input type="button" id="insetButton" class="btn" value="导入数据"></form></body></html>

后台代码:

@RequestMapping(value="/readExcel")@ResponseBodypublic String readExcel(HttpServletRequest request,@RequestParam("fileName")MultipartFile file) throws IOException{InputStream is = file.getInputStream();POIFSFileSystem fis = new POIFSFileSystem(is);HSSFWorkbook wb = new HSSFWorkbook(fis);HSSFSheet sheet = wb.getSheetAt(0);Iterator rows = sheet.iterator();if(rows.hasNext()){rows.next();//跳过表头,不循环第一行while(rows.hasNext()){HSSFRow row = (HSSFRow) rows.next();Iterator cells = row.iterator();int index = -1;while(cells.hasNext()){index++;HSSFCell cell = (HSSFCell) cells.next();switch (cell.getCellType()) {  case HSSFCell.CELL_TYPE_NUMERIC: // 数字  double test1 = ((Double)cell.getNumericCellValue()).intValue();break;  case HSSFCell.CELL_TYPE_STRING: // 字符串  String test2 = cell.getStringCellValue();  break;  case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean  boolean test3 = cell.getBooleanCellValue();  break;  default:  String test4 = cell.getStringCellValue(); break;  }}}}return null;}

在循环读取excel表格的时候,也可以用for循环,个人觉得for比while好操作数据些

for (int i = 1; i <= sheet.getLastRowNum(); i++) {if(null != sheet.getRow(i)){HSSFRow aRow = sheet.getRow(i);HSSFCell clazzCell = aRow.getCell(0);for (int j = 1; j <= aRow.getLastCellNum(); j++) {if(null != aRow.getCell(j)){HSSFCell aCell = aRow.getCell(j);String info = null;if(aCell.getStringCellValue() == null || aCell.getStringCellValue() == ""){info = " ";}else{info = aCell.getStringCellValue();}}}}}

看自家总在期待,不知将来好歹,新乐吧总在不断等待,

java 读取 excel

相关文章:

你感兴趣的文章:

标签云: