前言: 在各种项目中,总是会遇到 生成excel的需求,于是 我们必须要掌握对excel的读写,所以我粗浅的认为这是java的入门基础
1.首先导包
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
2.然后开始撸代码:用java在e盘创建一个如图的excel
先看poi的写法
public static void WriteExcel() throws Exception{
String [] title={"id","name","age"};
// 创建工作薄
HSSFWorkbook hssfWorkbook=new HSSFWorkbook();
// 创建要一个工作
HSSFSheet sheet=hssfWorkbook.createSheet();
//创建一行
HSSFRow row=sheet.createRow(0);
HSSFCell cell=null;// 每一小格
这是 列头的名字
for(int i=0; i<title.length;i++){
cell=row.createCell(i);
cell.setCellValue(title[i]);
}
// 追加数据
for(int i=1;i<=6;i++){
// 这是每一行
HSSFRow nextrow=sheet.createRow(i);
HSSFCell cell1=nextrow.createCell(0);//第几列
cell1.setCellValue("a"+1);
cell1=nextrow.createCell(1);//第几列
cell1.setCellValue("user"); 值
cell1=nextrow.createCell(2);
cell1.setCellValue("23岁");
}
// 写入 流中
File file=new File("e:/poi.xls");
FileOutputStream stream= FileUtils.openOutputStream(file);
hssfWorkbook.write(stream);
stream.close();
}
********************读出excel中的数据*******
File file=new File("e:/poi.xls");
HSSFWorkbook workbook=new HSSFWorkbook(FileUtils.openInputStream(file));
HSSFSheet sheet=workbook.getSheetAt(0);
int fristRow=0;
int laseRow=sheet.getLastRowNum();//最大行号
for(int i=fristRow;i<=laseRow;i++){
HSSFRow row=sheet.getRow(i);
int lastcellnum=row.getLastCellNum();// 每一行的最大的列
for(int j=0;j<lastcellnum;j++){
HSSFCell cell=row.getCell(j);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println("");
}
3.
归纳就是 :按照以下的顺序去写 去读就行
HSSFWorkBook---> HSSFSheet---> HSSFRow ---> HSSFCell---》cellValue(内容)