1、项目依赖jar包
poi-ooxml-3.9-20121203.jar
2、项目Excel模板
3、代码实现
package com.neusoft.tax.szrs.zzszda.job;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws Exception {
String fileName="test.xlsx";
List<List> rowList=new ArrayList<List>();
for(int i=0;i<5;i++) {
List<String> cellList=new ArrayList<String>();
cellList.add("姓名"+i);
cellList.add("姓别"+i);
cellList.add("年龄"+i);
rowList.add(cellList);
}
String outFileName="outTest.xlsx";
String filePath = downloadExcel(fileName,outFileName,rowList);
}
/**
* Excel文件生成
* @param inFileName
* @param outFileName
* @param rowList
* @return
*/
private static String downloadExcel(String inFileName,String outFileName,List<List> rowList) {
String filePath="";
String targetPath = "D:\\";
filePath=targetPath+outFileName;
FileInputStream file;
try {
file = new FileInputStream(targetPath+inFileName);
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
for(int i=0;i<rowList.size();i++) {
row = sheet.createRow(i+1);
List cellList=rowList.get(i);
for(int j=0;j<cellList.size();j++) {
cell = row.createCell(j);//姓名
cell.setCellValue((String)cellList.get(j));
cell.setCellStyle(cellStyle);
}
}
FileOutputStream out = new FileOutputStream(new File(filePath));
workbook.write(out);
out.close();
file.close();
} catch (Exception e) {
filePath="";
e.printStackTrace();
}
return filePath;
}
}