您的位置:首页 > 运维架构 > Apache

Apache POI读取和创建Excel ----01(简单操作)

2017-11-16 17:35 507 查看
public class ExcelCreatAndRead {

/**
* 使用Apache POI创建Excel文档
* */
public static void createXL(){
/**Excel文件要存放的位置,假定在D盘下*/
String outputFile="D:\\test.xlsx";
try {
//创建新的Excel工作薄
XSSFWorkbook workbook =new XSSFWorkbook();

//在Excel工作薄建一工作表,其名为缺省值
// HSSFSheet sheet=workbook.createSheet();
//在Excel工作薄建一工作表,其名为“测试”
XSSFSheet sheet=workbook.createSheet("测试");

//创建第一行
XSSFRow row =sheet.createRow(0);
// row.createCell(0).setCellValue("学员信息");

//合并单元格
// sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));

//在索引0的位置创建行(第一行)
XSSFRow row1=sheet.createRow(0);

//在索引0的位置创建列(第一列)
XSSFCell cell=row1.createCell(0);//画横线是代表此方法已过时,不建议使用;

//定义单元格为字符串类型(Excel-设置单元格格式-数字-文本;不设置默认为“常规”,也可以设置成其他的,具体设置参考相关文档)
cell.setCellType(HSSFCell.CELL_TYPE_STRING);

//在单元格内输入一些内容
cell.setCellValue("姓名");
row1.createCell(1).setCellValue("年龄");

//创建第二行:
XSSFRow row2=sheet.createRow(1);
row2.createCell(0).setCellValue("张三");
row2.createCell(1).setCellValue(18);

//创建第三行:
XSSFRow row3=sheet.createRow(2);
row3.createCell(0).setCellValue("李四");
row3.createCell(1).setCellValue(20);

//新建一输出文件流
FileOutputStream fout=new FileOutputStream(outputFile);

//把相应的Excel工作薄存盘
workbook.write(fout);

//flush();
//java在使用流时,都会有一个缓冲区,按一种它认为比较高效的方法来发数据:把要发的数据先放到缓冲区,缓冲区放满以后再一次性发过去,而不是分开一次一次地发.
//而flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满.
//所以如果在用流的时候,没有用flush()这个方法,很多情况下会出现流的另一边读不到数据的问题,特别是在数据特别小的情况下.
fout.flush();

//操作结束,关闭文件
fout.close();
System.out.println("文件生成");

} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("已运行 xlCreate():"+e);
}

}
/**读取Excel内容
* @throws FileNotFoundException */
public static void readExcel() throws FileNotFoundException{
FileInputStream file=new FileInputStream("D:\\test.xlsx");

try {
XSSFWorkbook workbook =new XSSFWorkbook(file);
XSSFSheet sheet=workbook.getSheet("测试");
XSSFRow row =sheet.getRow(0);
XSSFCell cell=row.getCell(0);
System.out.println(cell.getStringCellValue());

} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("已运行 readExcel():"+e);
}

//把导入的内容存在集合中里
List temp =new ArrayList();
try {
XSSFWorkbook workbook =new XSSFWorkbook(new FileInputStream("D:\\test.xlsx"));
XSSFSheet sheet=workbook.getSheet("测试");
for(Row r:sheet){
if(r.getRowNum()<1){
continue;
}
String name=r.getCell(0).getStringCellValue();
int age=(int) r.getCell(1).getNumericCellValue();
temp.add(name);
temp.add(age);
}

file.close();

//遍历list temp
Iterator it = temp.iterator();
while(it.hasNext()) {
System.out.print(it.next()+" ");
}
System.out.println();
System.out.println("读取完成");

} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("已运行readExcel"+e);
}

}
public static void main(String[] args) throws FileNotFoundException {
createXL();//创建Excel文档

readExcel();//读取Excel内容
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  学习记录