——邊學習邊記錄~
最近需要用到從外部文件導入測試數(shù)據(jù)钢坦,因而上網查了一些讀取excel文件這方面的代碼,然后修改后適用于現(xiàn)有場景中(得到excel中指定單元格的內容)啥酱。
導入的jar:poi-3.16.jar?
下載?poi-bin-3.16-20170419.tar.gz? 官網下載地址:http://poi.apache.org/download.html
//以下是因為長數(shù)字取出來變成了科學計數(shù)法形式爹凹,所以使用DecimalFormat進行格式化為數(shù)字
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的靜態(tài)方法,可以直接訪問
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) {
// 以下是判斷數(shù)據(jù)的類型禾酱,調對應的方法
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 數(shù)字
// cellValue = cell.getNumericCellValue() + "";
cellValue = df.format(cell.getNumericCellValue()); //長數(shù)字取出來變成了科學計數(shù)法形式,使用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);
}
}