您的位置:首页 > 其它

poi读取excel文件(.xsl或.xslx)实例,对日期和数字读取的处理,以及远程url和本地地址的区别

2016-09-02 17:45 639 查看
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
//import java.net.URL;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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 ImportExcel {

public int read(String path,String fileName,String fileType) throws IOException
{
InputStream stream = new FileInputStream(path+fileName+"."+fileType);
//      URL url = new URL(path+fileName+"."+fileType); 如果是远程地址:http://....则需要转化成url格式
//		stream = url.openStream();
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格式不正确");
}
System.out.println(wb.getNumberOfSheets());
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
if(row.getRowNum()==0){//第一行标题不读取
continue;
}
//这是不循环来取这行的单元格值,与下面循环一样,需要注意的地方是,如果某行有时间读入,则该行不能cell.setCellType(Cell.CELL_TYPE_STRING);转成String,否则会报错
//建议使用这个一格一格的取,不用下方注掉的循环,这样好对某个格子进行操作,要取某列的值就row.getCell(i)
row.getCell(0).getStringCellValue();//后面依次类似的取值
System.out.println(row.getCell(0).getStringCellValue());
//如果该行是数字则需要先处理再取值
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);//把数字转成字串
row.getCell(1).getStringCellValue();
System.out.println(row.getCell(1).getStringCellValue());
//如果该行是日期,同样是需要先处理,否则会报错
if (HSSFDateUtil.isCellDateFormatted(row.getCell(11))) {// 处理日期格式、时间格式
SimpleDateFormat sdf = null;
sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = row.getCell(11).getDateCellValue();
String a =sdf.format(date);//根据需要取时间,date类型和String类型
System.out.println(a);

}
//            for (Cell cell : row) {//遍历一行从0开始取出这行的每个单元格
//            	cell.setCellType(Cell.CELL_TYPE_STRING);//预先将该行类型转为string,预防有数字类型的值取不出来
//                System.out.print(c
4000
ell.getStringCellValue()+"  ");
//            }

}
return 0;
}

public static void main(String[] args) throws IOException {
String path = "E:/";
String fileName = "haha";
String fileType = "xlsx"; //路径拼全E:/haha.xlsx
ImportExcel test = new ImportExcel();
test.read(path, fileName, fileType);
}

}

pom.xml中引入poi依赖:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>3.9</version>
</dependency>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐