——边学习边记录~
最近需要用到从外部文件导入测试数据,因而上网查了一些读取excel文件这方面的代码,然后修改后适用于现有场景中(得到excel中指定单元格的内容)。
导入的jar:poi-3.16.jar
下载 poi-bin-3.16-20170419.tar.gz 官网下载地址:http://poi.apache.org/download.html
//以下是因为长数字取出来变成了科学计数法形式,所以使用DecimalFormat进行格式化为数字
DecimalFormat df = new DecimalFormat("0");
cellValue = df.format(cell.getNumericCellValue());
代码如下:
package com.test.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* 读取excel文件内容
* @author study_monkey
*
*/
public class ReadExcelFileInfo {
private static final ReadExcelFileInfo instance = new ReadExcelFileInfo();
private ReadExcelFileInfo(){
//do something
}
//这里提供了一个供外部访问本class的静态方法,可以直接访问
public static ReadExcelFileInfo getInstance(){
return instance;
}
public String readFile(int cellIndex,int rowIndex) {
String str = "";
InputStream fis = null;
try{
fis = new FileInputStream(new File("testdata.xls"));//File(path)
HSSFWorkbook workbook = new HSSFWorkbook(fis);
str = getValue(workbook,cellIndex,rowIndex);
}catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
fis = null;
e.printStackTrace();
}
}
}
return str;
}
public String getValue(HSSFWorkbook workbook,int cellIndex,int rowIndex) {//从0开始,行和列
String cellValue = "";
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(rowIndex);
HSSFCell cell = row.getCell((short) cellIndex);
DecimalFormat df = new DecimalFormat("0");
if (null != cell) {
// 以下是判断数据的类型,调对应的方法
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
// cellValue = cell.getNumericCellValue() + "";
cellValue = df.format(cell.getNumericCellValue()); //长数字取出来变成了科学计数法形式,使用DecimalFormat格式化
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
return cellValue;
}
public static void main(String[] args) {
ReadExcelFileInfo r = new ReadExcelFileInfo();
String str1 = ReadExcelFileInfo.instance.readFile(1,1);//index从0开始,获取第1行,第1列的内容
String str2 = ReadExcelFileInfo.instance.readFile(1,2);
System.out.println(str1);
System.out.println(str2);
}
}
网友评论