第一步:maven依赖导入:
org.apache.poi poi4.1.1 org.apache.poi poi-ooxml4.1.1 net.sf.saxon saxon-dom8.7
第二步:创建实体类ExcelVo
public class ExcelVo {
//text 写入内容
public String text;
//sheetIndex 第几个sheet页
public int sheetIndex;
//writeRow 写入横坐标 java从0开始
public int writeRow;
//writeCell 写入纵坐标 java从0开始
public int writeCell;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getSheetIndex() {
return sheetIndex;
}
public void setSheetIndex(int sheetIndex) {
this.sheetIndex = sheetIndex;
}
public int getWriteRow() {
return writeRow;
}
public void setWriteRow(int writeRow) {
this.writeRow = writeRow;
}
public int getWriteCell() {
return writeCell;
}
public void setWriteCell(int writeCell) {
this.writeCell = writeCell;
}
}
第三步:
public class PoiWriteExcel {
public static Workbook wb = null;
public static void WriteExcel(String path,int sheetIndex,String text,int writeRow,int writeCell ){
// wb = WorkbookFactory.create(new File(path));
wb= ExcelFormat(path);
Sheet sheet = wb.getSheetAt(sheetIndex);
Row row = sheet.getRow(writeRow);
if (null == row){
row = sheet.createRow(writeRow);
}
Cell cell = row.getCell(writeCell);
if (null==cell){
cell = row.createCell(writeCell);
}
cell.setCellValue(text);
SaveTemplate(path);
}
public static Workbook ExcelFormat(String path){
String suffix = path.substring(path.lastIndexOf("."));
try{
//根据后缀名判断
if(suffix.equals(".xlsx")){
wb = new XSSFWorkbook(new FileInputStream(path));//Excel 2007
}else if(suffix.equals(".xls")){
wb = new HSSFWorkbook(new FileInputStream(path));//Excel 2003
}
}catch(Exception e){
System.out.println("文件异常,异常信息是:"+e);
}
return wb;
}
public static void SaveTemplate(String filePath) {
FileOutputStream fileOutputStream = null;
try{
//建立输出流(这里也是你给一个你希望写入的文件路径)
fileOutputStream = new FileOutputStream(filePath);
wb.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
wb.close();
}catch(Exception e){
e.printStackTrace();
System.out.println("文件输出异常,异常信息:" + e);
}finally {
if (fileOutputStream !=null){
try {
fileOutputStream.close();
wb.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件关闭异常,异常信息:" + e);
}
}
}
}
public static void cycleWrite(String path,List list){
if (0 != list.size()){
for (ExcelVo excel: list) {
WriteExcel(path,excel.getSheetIndex(),excel.getText(),excel.writeRow,excel.getWriteCell());
}
}else {
System.out.println("写入集合不能为空");
}
}
} 


