使用POI工具包解析不同版本的Excel,代码如下:
public class ExcelPOI {
/**
*
* @Description:读取excel文件
* @param filePath
* @throws Exception: 返回结果描述
* @return void: 返回值类型
* @throws
*/
public void readExcel(String filePath) throws Exception{
InputStream is=new FileInputStream(filePath);
Workbook wb=getWorkbook(is,"read");
Sheet st=null;
Row row=null;
Cell cell=null;
int begin=0;
int end=0;
System.out.println(wb);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
st=wb.getSheetAt(i);
begin=st.getFirstRowNum()+1;
end=st.getLastRowNum();
for (int j = begin; j <= end; j++) {
row=st.getRow(j);
int beginC=row.getFirstCellNum();
int endC=row.getLastCellNum();
for (int k = beginC; k < endC; k++) {
cell=row.getCell(k);
if(cell!=null){
System.out.print(cell.getStringCellValue()+"\t");
}
}
System.out.println();
}
}
is.close();
}
/**
*
* @Description:根据Excel的版本创建Workbook
* @param is
* @return
* @throws Exception: 返回结果描述
* @return Workbook: 返回值类型
* @throws
*/
protected Workbook getWorkbook(InputStream is,String flag) throws Exception{
if(!is.markSupported()){
is=new PushbackInputStream(is,8);
}
if(POIFSFileSystem.hasPOIFSHeader(is)) {
if("write".equals(flag)){
return new HSSFWorkbook();
}else if("read".equals(flag)){
return new HSSFWorkbook(is);
}
}
if(POIXMLDocument.hasOOXMLHeader(is)) {
if("write".equals(flag)){
return new XSSFWorkbook();
}else if("read".equals(flag)){
return new XSSFWorkbook(OPCPackage.open(is));
}
}
return null;
}
/**
*
* @Description:写excel文件
* @param filePath
* @throws Exception: 返回结果描述
* @return void: 返回值类型
* @throws
*/
public void writeExcel(String filePath) throws Exception{
InputStream is=new FileInputStream(filePath);
Workbook wb=getWorkbook(is,"write");
Sheet st=wb.createSheet("Sheet01");
Row row=null;
Cell cell=null;
String[][] content={
{"名字","性别","爱好","电话"},
{"xiaoyi","女","打羽毛球","123"},
{"xiaoming","男","打羽毛球","123"},
{"admin","女","打羽毛球","123"},
{"xiaohong","女","打羽毛球","123"}
};
row=st.createRow(0);
cell=row.createCell(0);
cell.setCellValue("信息表");
for (int i = 1; i <= content.length; i++) {
row=st.createRow(i);
for (int j = 0; j < content[i-1].length; j++) {
cell=row.createCell(j);
cell.setCellValue(content[i-1][j]);
}
}
OutputStream os = new FileOutputStream(filePath);
wb.write(os);
os.close();
}
}