<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
将对象写入excel并将excel输出(三)
//将对象信息写入excel表中
public XSSFWorkbook show1(String oldPath) throws Exception {
//调用该类中的insertTxts方法,获取对象集合list
List<ImportTxtEntity> list = insertTxts(oldPath);
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Goods");//创建一张表
Row titleRow = sheet.createRow(0);//创建第一行,起始为0
titleRow.createCell(0).setCellValue("序号");//第一行第一列
titleRow.createCell(1).setCellValue("你的名字");//第一行第二列,以此类推
titleRow.createCell(2).setCellValue("你的年龄");
int cell = 1;
for (ImportTxtEntity importTxtEntity : list) {
Row row = sheet.createRow(cell);//从第二行开始保存数据
row.createCell(0).setCellValue(cell);//第二行第一列
row.createCell(1).setCellValue(importTxtEntity.getName());//第二行第二列,以此类推
row.createCell(2).setCellValue(importTxtEntity.getAge());
cell++;
}
//返回一个有值的excel表
return wb;
}
//这是所有代码的主入口
public void createExcelOne() throws Exception {
//这是生成excel文件的名字
String name = "F:\\Desktop\\a\\帅比.xlsx";
//这是调用该类中的show1方法生成相应的excel表格,需要传入txt所在的文件夹的位置
XSSFWorkbook listExcel = show1("D:\\帅比所在的文件夹");
try{
// 判断这个文件夹是否存在,如果不存在就生成该文件夹
File file = new File("F:\\Desktop\\a");
if(file.exists() || !file.isDirectory()) {
file.mkdirs();
}
//将调用show1方法生成的文件夹进行输出到指定位置
FileOutputStream outputStream = new FileOutputStream(new File(name));
listExcel.write(outputStream);
//关闭输出流
outputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}