**
java使用jxl读取excel文件
**
java使用jxl库读取excel文件,本文中的excel文件后缀名为.xls,不支持.xlsx。
代码如下:
public class ExcelReader {
Workbook rwb;
public String[][] readExcel(String filePath) throws IOException {
if (filePath.endsWith(".xls")) {
return this.reader(filePath);
} else {
return null;
}
}
public String[][] reader(String filePath) throws IOException {
try{
InputStream is = new FileInputStream(filePath);
rwb = jxl.Workbook.getWorkbook(is);
Sheet readsheet = rwb.getSheet(0);
int rsColumns = readsheet.getColumns();
int rsRows = readsheet.getRows();
String[][] data = new String[rsRows][rsColumns];
for(int i = 0; i < rsRows; i++)
{
for(int j = 0; j < rsColumns; j++)
{
data[i][j] = readsheet.getCell(j, i).getContents();
}
}
return data;
} catch(Exception e){
e.printStackTrace();
return null;
} finally {
rwb.close();
}
}
如果为数值型,Cell。getContents()将四舍五入自动保留小数点后三位,如果需要更高精度,使用下面代码读取:
Cell cell = readsheet.getCell(j, i);
if(cell.getType() == CellType.NUMBER)
{
NumberCell numberCell = (NumberCell) cell;
data[i][j] = String.valueOf(numberCell.getValue());
}