1. 程式人生 > >java讀取excel表格並格式化輸出

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<row.getLastCellNum();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());
}
}


}