第一步:maven依赖导入:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>net.sf.saxon</groupId> <artifactId>saxon-dom</artifactId> <version>8.7</version> </dependency>
第二步:创建实体类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; /** * 写入workbook * @param path 文件路径 * @param sheetIndex 第几个sheet页 * @param text 写入内容 * @param writeRow 写入横坐标 java从0开始 * @param writeCell 写入纵坐标 java从0开始 */ 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); } /** * 判断文件格式 * @param path 文件路径 * @return */ 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; } /** * 文件写入excle * @param filePath */ 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); } } } } /** * 循环写入excel表格 * @param path * @param list */ public static void cycleWrite(String path,List<ExcelVo> list){ if (0 != list.size()){ for (ExcelVo excel: list) { WriteExcel(path,excel.getSheetIndex(),excel.getText(),excel.writeRow,excel.getWriteCell()); } }else { System.out.println("写入集合不能为空"); } } }