java應用poi讀取excel內容辦法實例。本站提示廣大學習愛好者:(java應用poi讀取excel內容辦法實例)文章只能為提供參考,不一定能成為您想要的結果。以下是java應用poi讀取excel內容辦法實例正文
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class FileOperator {
public static void main(String[] args) throws Exception {
String path = "F:\\1.xls";
print(path);
}
public static void print(String path) throws IOException{
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(new File(path)));
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;
HSSFSheet st = wb.getSheetAt(0);
for (int rowIndex = 0; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
for (short columnIndex = 0, size = row.getLastCellNum(); columnIndex <= size; columnIndex++) {
cell = row.getCell(columnIndex);
String value = "";
if (cell != null) {
// 留意:必定要設成這個,不然能夠會湧現亂碼
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 導入時假如為公式生成的數據則無值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
default:
value = "";
}
System.out.println(rowIndex + "," + columnIndex + ":"
+ value);
}
if (columnIndex == 0 && value.trim().equals("")) {
break;
}
}
}
}
}