IO操作_读取Excel

import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ReadExcel {

/**
*
* @param fileName 读取的Excel的名字
* @param sheetName sheet名字
* @param width 读取的列个数
* @return
*/
public static String[][] getInfoFromExcel(String fileName,String sheetName,int width){
try{


HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileName));

HSSFSheet sheet = workbook.getSheet(sheetName);

int rowNum = sheet.getLastRowNum();
String[][] ret = new String[rowNum][width];

for (int r = 0; r < rowNum; r++){
HSSFRow row = sheet.getRow(r);

for (int i = 0 ; i < width; i++)
ret[r][i] = row.getCell(i, HSSFRow.CREATE_NULL_AS_BLANK).toString().trim();


}

return ret;
}catch(Exception e) {
System.out.println("getInfoFromExcel : " + e );
}
return null;
}
/**
* 打印
* @param resultArr
* @param width
*/
private static void printArr(String[][] resultArr,int width){
for(int i=0;i System.out.print(i+1);
for(int j=0;j System.out.print("\t"+resultArr[i][j]);
}
System.out.println();
}
}
/**
* main测试
* @param args
*/
public static void main(String[] args){
String[][] resultArr = getInfoFromExcel("e:/switchLog/test.xls", "sheet_test",4);
printArr(resultArr,4);
}
}

你可能感兴趣的:(知识点积累)