通过apache poi这个jar包来实现读取excel的表格,程序是在servlet 运行,贴关键的代码
//项目根目录
String rootPath = this.getServletConfig().getServletContext().getRealPath("/");
//通过参数获取要读取的excel文件名
String filename = request.getParameter("filename");
//合成文件的绝对路径
String filestr = rootPath+filename;
File file = new File(filestr);
if(!file.exists())
{
System.out.println(filestr+"文件不存在");
return ;
}
else
{
System.out.println(filestr+"文件存在");
//文件存在 ,就打开文件
InputStream inp = new FileInputStream(filestr);
Workbook wb=null;
try {
wb = WorkbookFactory.create(inp);
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Workbook 创建失败");
return ;
}
//如果没有异常,定位到excel第一页
Sheet sheet = wb.getSheetAt(0);
//循环Row ,第一行是标题,跳过
for(int rowNum=1; rowNum<=sheet.getLastRowNum();rowNum++)
{
Row row = sheet.getRow(rowNum);
if(row==null)
{
continue;
}
//循环一行的cell,得到姓名和职务
String name="",position="";
for(int cellNum=0 ; cellNum<=row.getLastCellNum();cellNum++)
{
//获取第rowNum行的第cellNum个单元格
Cell cell = row.getCell(cellNum);
//如果单元格是空的,跳过
if(cell==null)
{
continue;
}
//获取值
String value = getValue(cell);
//跳过内容为空的 cell
if( "".equals( value.trim() ) )
{
continue;
}
if(cellNum==0)
{
name= value;
}
else
{
position=value;
}
}//循环一行结束
//打印出读取的内容
if(!"".equals(name) || !"".equals(position))
{
System.out.println("name:"+name+"\t position:"+position);
}
}//循环所有行结束
}//else结束
完整的demo 可以这个网址下载 http://download.csdn.net/detail/ch717828/8363373
参考文章:http://hao0610.iteye.com/blog/1160678
http://sarin.iteye.com/blog/845035
http://sarin.iteye.com/blog/846679
http://blog.csdn.net/hehexiaoyou/article/details/37873131