java读取excel表格并格式化输出

首先是需要poi  jar包

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class ReadExcel {


private static String substring;


public static void main(String[] args) {
try {

//输入文件名
ReadExcel.read("D:1.xlsx");
} catch (IOException e) {
e.printStackTrace();
}
}


public static void read(String filePath) throws IOException {
//判断是xls  还是xlsx
String fileType = filePath.substring(filePath.lastIndexOf(".") + 1,
filePath.length());
InputStream stream = new FileInputStream(filePath);
Workbook wb = null;
if (fileType.equals("xls")) {
wb = new HSSFWorkbook(stream);
} else if (fileType.equals("xlsx")) {
wb = new XSSFWorkbook(stream);
} else {
System.out.println("您输入的excel格式不正确");
}
//得到sheet1;
Sheet sheet1 = wb.getSheetAt(0);
// 遍历行除了第一行
for (int rownum=1;rownum<=sheet1.getLastRowNum();rownum++) {
Row row = sheet1.getRow(rownum);
StringBuffer sb = new StringBuffer();
//遍历单元格
for(int j=0;j

String value = null;
Cell cell = row.getCell(j);
//判断单元格是否为空
if(cell==null||cell.equals("")||cell.getCellType()==HSSFCell.CELL_TYPE_BLANK){
value="null";

}else

//判断数据类型

switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
value = "" + cell.getCellFormula();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
value = "" + cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
}
sb.append(value + ",");
substring = sb.substring(0, sb.length()-1);
}
//转换为数组
String[] strings = sb.toString().split(",");

System.out.println(substring.toString());
}
}


}

你可能感兴趣的:(java读取excel表格并格式化输出)