`
hsyzijvaa
  • 浏览: 107385 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Excel文件读取

    博客分类:
  • java
阅读更多
    java中要读取excel文件并解析。目前的excel文件主要是xls的97-2000格式和xlsx的2007格式。
以下提供简单的操作示例。
 
1,workbook
解析文件格式:xls
 
workbooksettings workbooksettings = new workbooksettings();        workbooksettings.setencoding("iso-8859-1");        stringbuffer s = new stringbuffer("");        list<string> l = new arraylist<string>();        try {			workbook book = workbook.getworkbook(new file("f:\\test2.xls"),workbooksettings);			sheet sheet = book.getsheet(0);//只读取excel的第一页			for (int i = 1; i < sheet.getrows(); i++) {				for(int j=0;j<sheet.getcolumns();j++){			    	 cell cell = sheet.getcell(j, i);// 第一列第i行			         string tmpvalue=cell.getcontents();			         tmpvalue=tmpvalue.replaceall("\177", "").replaceall("\\s", "");//公共组件excel导出时,单元值有加一个特殊字符,处理后,用导出的excel做查询条件才会正常			         s.append(tmpvalue+"||");				}				l.add(s.tostring());				s.delete(0, s.length());			}			for(string ss:l){				system.out.println(ss);			}		} catch (biffexception e) {			e.printstacktrace();		} catch (ioexception e) {			e.printstacktrace();		} 
 
 
2, poi-hssf
读取文件格式:xls
程序未终止时,可修改文件.
try{			inputstream input = new fileinputstream("f:\\testbatchopen.xlsx");			poifsfilesystem pf = new poifsfilesystem(input);			hssfworkbook wb = new hssfworkbook(pf);			hssfsheet sheet = wb.getsheetat(0);			sheet.removerow(sheet.getrow(0));			iterator rows = sheet.rowiterator();			while(rows.hasnext()){				hssfrow row = (hssfrow)rows.next();				system.out.print(row.getcell(0).tostring()+";");				system.out.print(row.getcell(1).tostring()+";");				system.out.print(row.getcell(2).tostring()+";");				system.out.print(row.getcell(3).tostring()+";");				system.out.print(row.getcell(4).tostring());				system.out.println();			}		}catch(exception e){			e.printstacktrace();		}
 
 
3,poi-xssf
读取文件格式:xlsx
try {inputstream in = new fileinputstream("f:/testbatchopen.xlsx");
			xssfworkbook xwb = new xssfworkbook(in);			// 读取第一章表格内容   			xssfsheet sheet = xwb.getsheetat(0); 			xssfrow row;			for(int i=sheet.getfirstrownum()+1;i<sheet.getlastrownum()+1;i++){				row = sheet.getrow(i);				system.out.print(row.getcell(0).tostring()+";");				system.out.print(row.getcell(1).tostring()+";");				system.out.print(row.getcell(2).tostring()+";");				system.out.print(row.getcell(3).tostring()+";");				system.out.print(row.getcell(4).tostring());				system.out.println();			}		} catch (ioexception e) {			e.printstacktrace();		}   
 
 
jar包:
workbook-jxl.jar
poi-hssf-poi-3.5-final-20090928.jar
poi-xssf-poi-ooxml-3.8-beta3-20110606.jar,poi-ooxml-schemas-3.8-beta3-20110606.jar
地址:http://poi.apache.org/
 
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics